猫鼬填充引用对象ID,而不是对象本身

问题描述 投票:0回答:1

背景

这是我的用户模型的一部分:

const Group = require("./Group")

...

groups: {
    type: [{ type: Schema.ObjectId, ref: Group }],
    default: [],
},

这是我的小组模型:

module.exports = mongoose.model(
    "Group",
    new Schema(
        {
            name: {
                type: String,
                required: true,
                unique: true,
            },

            /**
             * Array of User ObjectIDs that have owner rights on this group
             */
            owners: {
                type: [{ type: Schema.ObjectId, ref: User }],
                default: [],
            },
        },
        {
            timestamps: true,
        }
    )
)

代码

这是我要尝试填充的代码:

const user = await (await User.findOne({ _id: ... })).execPopulate("Group")
console.log(user.groups)

当我希望它输出实际的组文档时,我的console.log正在输出对象ID的数组。

尝试的解决方案

[我尝试将ref更改为使用字符串("Group"),尝试将查询安排为其他方式,等等。我不确定如何去做。

如果这是重复的话,请提前道歉,我已尽力进行搜索,但实际上找不到适合我的解决方案。

具体来说,我需要什么帮助?

我正在尝试在用户模型和组模型之间创建“链接”。我希望在console.log中,它可以输出一个Group文档;但它会输出一个对象ID(这是将其原始存储在数据库中的方式,这意味着Mongoose无法正确转换它)]

javascript node.js mongodb mongoose
1个回答
0
投票

当您将execPopulate更改为populate时:

async function findUserAndPopulate(userId){
  const response = await User.findOne({
    _id: userId,
  }).populate('groups')


  console.log("response",response)
}

您得到了:

{
  groups: [
    {
      owners: [Array],
      _id: 5ecc637916a2223f15581ec7,
      name: 'Crazy',
      createdAt: 2020-05-26T00:31:53.379Z,
      updatedAt: 2020-05-26T00:31:53.379Z,
      __v: 0
    }
  ],
  _id: 5ecc6206820d583b99b6b595,
  fullname: 'James R',
  createdAt: 2020-05-26T00:25:42.948Z,
  updatedAt: 2020-05-26T00:36:12.186Z,
  __v: 1
}

因此您可以访问user.groups

请参阅文档:https://mongoosejs.com/docs/populate.html

© www.soinside.com 2019 - 2024. All rights reserved.