我不能手动或自动填充一个新保存的对象的创建者字段... 唯一的方法,我可以找到是重新查询对象,我已经有,我讨厌这样做。
这是设置:
var userSchema = new mongoose.Schema({
name: String,
});
var User = db.model('User', userSchema);
var bookSchema = new mongoose.Schema({
_creator: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
description: String,
});
var Book = db.model('Book', bookSchema);
这就是我扯头发的地方
var user = new User();
user.save(function(err) {
var book = new Book({
_creator: user,
});
book.save(function(err){
console.log(book._creator); // is just an object id
book._creator = user; // still only attaches the object id due to Mongoose magic
console.log(book._creator); // Again: is just an object id
// I really want book._creator to be a user without having to go back to the db ... any suggestions?
});
});
编辑: 最新的猫鼬修复了这个问题,并添加了填充功能,见新的接受的答案。