【问题标题】:Mongoose return id instead of _id in populate methodMongoose 在填充方法中返回 id 而不是 _id
【发布时间】:2020-08-15 00:34:35
【问题描述】:

我有两个相关的模型:Recipe 和 User。

当我使用populate() 从数据库中获取配方和相关用户时,我希望返回的用户对象具有id 属性而不是_id 属性。

const recipe = await Recipe.findOne({ _id }).populate('user', '-password');

当我记录用户模型的值时,我想得到这个:

{
  id: 5eea82b11a97e9429ca61778,
  name: 'John Doe',
  email: 'johndoe@gmail.com'
}

我尝试将id 属性添加到用户对象,它没有改变任何东西。我仍然拥有_id 属性。

recipe.user = { ...recipe.user, id: recipe.user_id };

【问题讨论】:

  • 你有什么特别的原因想要id而不是_id吗?
  • @Shadab 在我的应用程序的其他部分,我可以使用id 而不是_id,但它在这种填充方法中不起作用。为了保持一致性,我想使用id 而不是_id。

标签: node.js mongodb mongoose mongoose-populate


【解决方案1】:
    noteSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

这是我用来删除下划线的 - 你可以转换文档并删除你不想要的位

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-04
    • 2013-06-30
    • 2018-07-07
    • 2014-12-12
    • 2015-03-06
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多