首页 > 解决方案 > 返回的文档显示意外值

问题描述

我使用定义了以下架构Mongoose

  const IndustryPartnerSchema = new Schema({
  mentors: [{ user: { type: Schema.Types.ObjectId, ref: "User" } }],
});

module.exports = IndustryPartner = mongoose.model(
  "IndustryPartner",
  IndustryPartnerSchema
);

我将以下内容存储在我的数据库中

 "mentors" : [
        ObjectId("5c9ba825347bb645e0865293")
    ]

但是,当我使用查询数据库时,

   IndustryPartner.findOne({ _id: req.query.partnerId })
      .populate("mentors")

我得到以下信息:

{ "mentors": []}

如果我删除.populate("mentors"),我会得到以下信息:

  "mentors": [
        {
            "_bsontype": "ObjectID",
            "id": {
                "type": "Buffer",
                "data": [
                    92,
                    155,
                    168,
                    37,
                    52,
                    123,
                    182,
                    69,
                    224,
                    134,
                    82,
                    147
                ]
            }
        }
    ]

我必须缺少一些东西,我知道 ObjectId 是有效的,因为我手动搜索了我的数据库并且它是一个有效的用户文档。为什么这实际上没有填充该字段?

谢谢!

标签: mongodbmongoose

解决方案


mentors架构中的字段是一个对象数组,user字段为 ObjectId,因此您在数据库中的记录与架构不匹配。由于您已经在数据库中保存了记录,因此您需要像下面这样更改您的架构以使其工作:

const IndustryPartnerSchema = new Schema({
  mentors: [{ type: Schema.Types.ObjectId, ref: "User" }],
});

推荐阅读