当尝试填充一个字段时,返回的所有内容都是最初为该字段保存的 objectid
在 models/gifts.js
var GiftSchema = new Schema({
name: String,
owner: {
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: false
},
nonRegisteredEmail: {
type: String,
required: false
},
nonRegisteredName: {
type: String,
required: false
}
},
description: String,
url: String
}
});
module.exports = mongoose.model('Gift', GiftSchema);
Run Code Online (Sandbox Code Playgroud)
在 models/user.js
var UserSchema = new Schema({
name: String,
email: { type: String, lowercase: true },
role: {
type: String,
default: 'user'
},
hashedPassword: String,
provider: String,
salt: String
});
module.exports = mongoose.model('User', UserSchema);
Run Code Online (Sandbox Code Playgroud)
我gift通过将_id用户添加到owner.user我的gift.
然后,当我尝试user在查询期间填充该字段时,仅_id返回该字段。前任5388bb3a82f0e4003100a6ba
exports.getAll = function (req, res) {
return Gift.find()
.populate({
path:'user',
model:'User'
})
.exec(function(err,gifts){
if(!err)
{
return res.json(gifts);
}
else{
return res.send(err);
}
});
};
Run Code Online (Sandbox Code Playgroud)
您要填充的路径是owner.user,而不仅仅是user,因此您应该更改以下内容:
return Gift.find()
.populate({
path:'user',
model:'User'
})
Run Code Online (Sandbox Code Playgroud)
对此:
return Gift.find()
.populate({
path:'owner.user',
model:'User'
})
Run Code Online (Sandbox Code Playgroud)