我简化了下面的代码:
var buySchema = new mongoose.Schema({
userid:String,
timestamp:Number,
price:Number
});
var cardSchema = new mongoose.Schema({
cardid: String,
buy:[{type:mongoose.Schema.Types.ObjectId, ref:'buy'}],
});
var Card = mongoose.model('cards',cardSchema,'cards');
var Buy = mongoose.model('buy',buySchema,'buy');
Card.findOne({'cardid':cardid}, function(err, card) {
var newBuy = new Buy({'userid':userid, timestamp:null,price:null});
newBuy.save(function(err){
card.buy.addToSet(newBuy._id);
});
card.save(function(err,card){
console.log(card.buy); // card.buy[] has an ObjectId ref
});
});
Card.findOne({'cardid':cardid}, function(err, card) {
console.log(card.buy); // !!!!! card.buy[] does not have ObjectId ref !!!!!
});
buy []似乎从未在mongodb中保存过ObjectId引用
如果没有ObjectId引用,以后如何填充卡?他们去哪了我不了解人口多少?
最佳答案
newBuy.save
调用是异步的,因此您的card.save
调用发生在card.buy.addToSet
调用之前。
因此,将代码的那部分重新排序为:
newBuy.save(function(err){
card.buy.addToSet(newBuy._id);
card.save(function(err,card){
console.log(card.buy);
});
});
要么
newBuy.save(function(err){
});
card.buy.addToSet(newBuy._id);
card.save(function(err,card){
console.log(card.buy);
});
关于node.js - Mongoose 人口ObjectId引用消失了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23929377/