保存后猫鼬填充 [英] Mongoose populate after save
问题描述
我无法在新保存的对象上手动或自动填充创建者字段......我能找到的唯一方法是重新查询我不想做的我已经拥有的对象.
I cannot manually or automatically populate the creator field on a newly saved object ... the only way I can find is to re-query for the objects I already have which I would hate to do.
这是设置:
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?
});
});
最新的猫鼬修复了这个问题并添加了填充功能,请参阅新的已接受答案.
latest mongoose fixed this issue and added populate functionality, see the new accepted answer.
推荐答案
您应该能够使用模型的 populate 函数来执行此操作:http://mongoosejs.com/docs/api.html#model_Model.populate 在书籍的保存处理程序中,而不是:
You should be able to use the Model's populate function to do this: http://mongoosejs.com/docs/api.html#model_Model.populate In the save handler for book, instead of:
book._creator = user;
你会做这样的事情:
Book.populate(book, {path:"_creator"}, function(err, book) { ... });
可能为时已晚,无法为您提供帮助,但我最近陷入了困境,这可能对其他人有用.
Probably too late an answer to help you, but I was stuck on this recently, and it might be useful for others.
这篇关于保存后猫鼬填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!