问题
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