【问题标题】:Mongoose populate referencing object id, not the object itselfMongoose 填充引用对象 ID,而不是对象本身
【发布时间】:2020-09-12 05:32:35
【问题描述】:

背景

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

const Group = require("./Group")

...

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

这是我的 Group 模型:

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 的数组,而我希望它输出一个实际的 Group 文档。

尝试的解决方案

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

如果这是重复的,请提前道歉,我已尽力搜索,但无法真正找到适合我的解决方案。

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

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

【问题讨论】:

  • 您的问题我不清楚。您能否澄清您的问题、预期输出和实际输出?
  • @JairusMartin 我正在尝试在用户模型和组模型之间创建“链接”。在我的console.log 中,我希望它输出一个组文档;但它会输出一个对象 ID(这是它在数据库中的原始存储方式,这意味着 Mongoose 没有正确转换它)
  • 如果可以请更新您的问题,您更有可能得到社区的回复。
  • @JairusMartin 完成!
  • 看起来您的问题与如何declare 两个模型之间的关系有关,以便您可以访问关联模型,如 user.groups.name。

标签: javascript node.js mongodb mongoose


【解决方案1】:

当您将 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

【讨论】:

    猜你喜欢
    • 2014-03-07
    • 2019-06-23
    • 2017-10-03
    • 2021-06-29
    • 2020-06-01
    • 2018-08-11
    • 2018-07-08
    • 2018-06-11
    • 2023-04-01
    相关资源
    最近更新 更多