【问题标题】:How to populate a referenced document from `this` object?如何从 `this` 对象填充引用的文档?
【发布时间】:2020-07-13 15:30:58
【问题描述】:

我正在使用 NodeJS、MongoDB 和 Mongoose。如果我使用findById(this.id),但不能直接使用this,我可以填充引用的文档:

IssuanceSchema.methods.getOrganizationName = async function() {

  let issuance = await Issuance.findById(this.id).populate('organization');
  console.log(issuance);
  let temp = this.populate('organization');
  console.log(temp);

  console.log(issuance.organization.displayName());
  console.log(temp.organization.displayName());
  // ...
}

日志显示:

{ _id: 5e849ca9b07ed81bd2eaad89, 组织: { _id: 5e80a19d8c910f196c11673c, ... }, } { _id: 5e849ca9b07ed81bd2eaad89, 组织:5e80a19d8c910f196c11673c, } 某个名字 (node:10231) UnhandledPromiseRejectionWarning: TypeError: temp.organization.displayName is not a function

我怎样才能直接填充引用的文档而无需迂回findById

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您似乎只是错过了对execPopulate() 的呼叫。你的情况是:

    let temp = this.populate('organization').execPopulate();
    

    查看the docs:

    如果您有一个现有的 mongoose 文档并且想要填充它的一些路径,您可以使用 Document#populate() 方法。只要确保您调用Document#execPopulate() 来执行populate()

    【讨论】:

      猜你喜欢
      • 2013-07-08
      • 2015-07-28
      • 2020-04-30
      • 2019-01-08
      • 1970-01-01
      • 2015-06-04
      • 2018-03-19
      • 2020-08-09
      • 1970-01-01
      相关资源
      最近更新 更多