1

Hi i have some problems with mongodb.

const mongoose = require('mongoose');

const companySchema = new mongoose.Schema({
  name: String,
  url: String,
  images: Array
});

const categoriesSchema = new mongoose.Schema({
  company: companySchema,
  name: String
});

module.exports = mongoose.model('categories', categoriesSchema);

above of code is model

    app.post('/addCompanyinfo', function (req, res){
        var news = new Categories();
        news.company[name]= req.body.company;  <--- here!
        news.save(function (err) {
            if(err) {
                console.error(err);
                res.json({result: 0});
                return;
            }
            res.json({result: 1})
        })
    })

and this is router code. and i want to access categoriesSchema-> company (companySchema)-> name.

how can i access company schema's 'name' ??

your help will be a big lucky in future to you :)

2 Answers 2

1

You need to create an Object for Company to assign its properties

var news = new Categories();
var company = new Company();
news.company = company;

news.name = 'test category'  
company.name = 'test company';

console.log(company);

console log

{ name: 'test category',
  company: { _id: 5a61629b74f8df0bd73142ba, images: [] },
  _id: 5a61629b74f8df0bd73142b9 }


{ name: 'test company', _id: 5a61629b74f8df0bd73142ba, images: [] }
Sign up to request clarification or add additional context in comments.

Comments

0

You can post your data in json format and use bodyParser.json() middleware in your app.js, and your backend code can be this:

router.post('/', function(req, res, next) {
  var news = new Categories(req.body); // create record directly with the json data
  console.log(req.body.company.name);  //just access it directly

  news.save(function (err) {
      if(err) {
          console.error(err);
          res.json({result: 0});
          return;
      }
      res.json({result: 1});
  });
});

and json format can be this:

{
  "company": {
      "name": "test company name",
      "url": "http://test.com",
      "image": []
  },
  "name": "test name"
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.