jieun
jieun

Reputation: 27

how can i access mongodb document's array? (mongodb, nodejs)

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 :)

Upvotes: 1

Views: 58

Answers (2)

Saravana
Saravana

Reputation: 12817

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: [] }

Upvotes: 1

David Wei
David Wei

Reputation: 172

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"
}

Upvotes: 0

Related Questions