Xeul Xeul - 1 year ago 141
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
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:

  .findOne({ name: 'name' })
  .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