【问题标题】:Mongoose: cannot access populated valueMongoose:无法访问填充值
【发布时间】:2017-03-23 04:34:32
【问题描述】:

我可以在控制台中看到填充的值,但是当我尝试访问它时,我得到了undefined

const AccountProfile = new Schema({
  owner: { type: String },
  firstName: { type: String },
  lastName: { type: String },
  countryId: { type: mongoose.Schema.Types.ObjectId, ref: "Country" }
});

const Country = new Schema({
    name: String
});

AccountProfile.statics.getProfile = function (username, cb) {
    this.model("AccountProfile").findOne({owner: username})
    .populate("countryId")
    .exec(function (err, profile) {
        if (err) {
            return cb(err);
        }
        console.log(profile.countryId);
        return cb(null, profile);
    });
};

输出格式如下:{ _id: 57a9d5cda3c91dda14eb50f0, Name: 'UK' }

打印profile.countryId._id 看起来不错,但profile.countryId.Nameundefined

有什么线索吗?使用猫鼬版本 4.6.6

【问题讨论】:

  • 检查key是否有空格
  • 你能显示国家模式吗?
  • @chridam 这似乎不是问题所在。 JSON.stringify(profile.countryId) 的输出是 {"_id":"57a9d5cda3c91dda14eb50f0","Name":"UK"}
  • @RizwanJamal 完成

标签: javascript node.js mongodb mongoose-populate


【解决方案1】:

在 Schema 中,您定义了字段“名称”而不是“名称” 尝试获取profile.countryId.name

【讨论】:

  • 但是你如何在控制台中获得“名称”......如果它没有在Country Schema中定义
  • 谢谢。问题是,在实际的 mongo 文档中,该字段被称为 Name,而在我的代码中为 name(我在将现有数据导入想要使用代码访问的 mongo 后创建了 mongoose 模式)。因此,我不得不将 mongoose 模式中的字段重命名为 Name 以与 mongo 中的内容保持一致。这就解释了为什么在控制台中打印了Name
猜你喜欢
  • 2016-07-11
  • 2018-12-12
  • 2021-02-28
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 2021-08-31
  • 2012-01-22
  • 2014-12-12
相关资源
最近更新 更多