Xeul Xeul - 1 year ago 124
Node.js Question

mongoose sub document access

How would you access the sub document on an already found document?

Let's say I create the following models:

const mongoose = require('mongoose');
const schema = mongoose.schema;

const barStructure = {
name: { type: String, require: true }
}

const fooStructure = {
name: { type: String, require: true }
bar: { type: schema.ObjectId, ref: 'bar', require: false }
}

var barModel = mongoose.model('bar', schema(barStructure);
var fooModel = mongoose.model('foo', schema(fooStructure);


and then create:

fooModel.create({ name: 'name', bar: new barModel({ name: 'name' }) });


Now how can I access
bar
from the parent?

fooModel.findOne({ name: 'name' }, (err, result) => {
//How can I access bar here?
});

Answer Source

You can use the Mongoose Query Population feature:

fooModel
  .findOne({ name: 'name' })
  .populate('bar')
  .exec((err, foo) => {
    if (err) return handleError(err);
    console.log(foo.bar): // Access sub model
  });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download