【问题标题】:Quick way to retrieve doc from other doc's ref in Mongoose (Node.js)在 Mongoose (Node.js) 中从其他文档的引用中检索文档的快速方法
【发布时间】:2017-05-22 19:18:49
【问题描述】:

我有一个模型Product,其引用字段为Grocer。在某些时候,我有Product 文档,但没有填充Grocer 字段,只有ObjectId。有没有一种使用猫鼬填充文档的快速方法?或者我必须以某种方式扩展它?,所以来自:

// product 'product1'
{
  _id: 'ksjdflasdf78aslwk3jk8df9',
  name: 'Product 1',
  grocer: 'jasf97342jlihwe79834hkjhdkf'
}

我可以这样做:

doc.populate('grocer');

现在文档是:

// product 'product1'
{
  _id: 'ksjdflasdf78aslwk3jk8df9',
  name: 'Product 1',
  grocer: {
    _id: 'jasf97342jlihwe79834hkjhdkf',
    name: 'Johan'
  }
}

【问题讨论】:

    标签: node.js mongodb mongoose populate ref


    【解决方案1】:

    我会回答自己,而不是删除问题。 Mongoose 从 v3.6 开始提供填充文档的选项。

    例子:

    // summary
    doc.populate(path)                   // not executed
    doc.populate(options);               // not executed
    doc.populate(path, callback)         // executed
    doc.populate(options, callback);     // executed
    doc.populate(callback);              // executed
    doc.populate(options).execPopulate() // executed, returns promise
    

    http://mongoosejs.com/docs/api.html#document_Document-populate

    【讨论】:

      猜你喜欢
      • 2018-06-20
      • 1970-01-01
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2015-05-25
      • 2013-03-22
      • 2023-03-18
      • 2021-10-01
      相关资源
      最近更新 更多