mongodb:如何填充单个嵌套的子文档

时间:2017-08-18 01:39:56

标签: node.js mongodb mongoose mongoose-populate

我正在使用mongodb和mongoose编写node.js应用程序。我似乎在理解如何查询"单个嵌套子文档"时遇到了问题。如果我有一个如下例子:

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
});
从mongoose文档中

,如何为单个嵌套方案填充子子文档?我尝试使用" .populate(" child")。exec ..."但是,即使我可以找到是否从mongo命令行运行db.child.find(),子对象仍返回null。现在我在文档中看到,你必须在哪里调用" parent.children.id(_id)"但在这种情况下,我不会提前知道_id。

更新:我删除了填充内容,它现在似乎正在运行。

1 个答案:

答案 0 :(得分:0)

您已将子文档作为嵌入文档存储在父文档中,因此无需填充。 Populate用于存储对运行查询时要填充的其他文档的引用的情况。这种情况的一个例子是:

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'
  }
});

现在,如果您在查询child时尝试填充parent,它应该有效。