Mongoose: cannot access populated value

…衆ロ難τιáo~ 提交于 2020-02-08 04:47:46

问题


I can see the populated value in the console but when trying to access it I'm getting 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);
    });
};

The output has the following format: { _id: 57a9d5cda3c91dda14eb50f0, Name: 'UK' }

Printing profile.countryId._id looks fine, but profile.countryId.Name is undefined!

Any clue? Using mongoose version 4.6.6


回答1:


In Schema you have defined the field "name" not "Name" Try with getting profile.countryId.name



来源:https://stackoverflow.com/questions/40505738/mongoose-cannot-access-populated-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!