简体   繁体   中英

mongodb: how to populate a single nested subdocuments

I am writing a node.js application using mongodb and mongoose. I seems to be having an issue in understanding how to query "single nested subdocuments". If I have an example like the following:

var childSchema = new Schema({ name: 'string' });

var parentSchema = new Schema({
  // Array of subdocuments
  children: [childSchema],
  // Single nested subdocuments. Caveat: single nested subdocs only work
  // in mongoose >= 4.2.0
  child: childSchema
});

from the mongoose documentation, how do I populate the child subdocument for a single nested scenario? I tried to use the ".populate("child").exec..." but the child object returns null even though I can find if I run db.child.find() from the mongo command line. Now I saw in the documentation, where you have to call "parent.children.id(_id)" but in this case I will not know the _id ahead of time.

Update: I removed the populate and it appears to be working now.

You are already storing the child document as embedded one inside the parent document, so there is no need to populate. Populate is for those cases where you are storing a reference to other document which you want to be populated while running the query. An example for such case would be :

var childSchema = new Schema({ name: 'string' });
var childModel = mongoose.model("child", childSchema);

var parentSchema = new Schema({
  // Array of subdocuments
  children: [childSchema],
  child: {
    type: Schema.ObjectId, ref: 'child'
  }
});

Now if you try to populate child while querying parent , it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM