You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mongoose 6.x移除execPopulate后save操作完成如何执行populate?

Mongoose 6及以上版本保存文档后执行populate的实现方案

Mongoose 6版本已正式移除execPopulate()方法,文档实例的populate()方法现在本身返回Promise,无需额外调用执行方法即可完成填充操作。

你原有代码的报错就是因为调用了已废弃的execPopulate(),直接删除该方法调用即可实现需求:

const t = new MyModel(value)
return t.save().then(t => t.populate('my-path'))

如果使用async/await语法,写法更清晰:

async function createAndPopulate(value) {
  const t = new MyModel(value)
  // 完成保存,此时可使用未填充实例执行其他逻辑
  await t.save()
  // 直接等待populate执行完成,原实例会被自动填充关联字段
  await t.populate('my-path')
  return t
}

该方案完全满足你的要求:

  • 填充前可正常使用刚创建的未填充实例执行自定义逻辑
  • 无需调用MyModel.populate()静态方法,直接操作文档实例即可

内容的提问来源于stack exchange,提问作者Eujin Ong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 22:45:02