1

我简化了下面的代码:

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 ref

如果没有 ObjectId refs,我以后应该如何填充卡片?他们去哪儿了?关于人口,我没有得到什么?

4

3 回答 3

1

您必须为 ref:'buy' 添加引号并添加正确的架构。看 mongoosejs文档

var cardSchema = new mongoose.Schema({
    cardid: String,
    buy:[{type:mongoose.Schema.Types.ObjectId, ref:'buy'}],
});

var Card = mongoose.model('cards',cardSchema);
var Buy = mongoose.model('buy',buySchema);
于 2014-05-29T09:10:06.470 回答
0

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);
});
于 2014-05-29T18:04:21.057 回答
0

因此,在保存孩子时,您必须将父母保存在孩子保存的回调中,如下所示:

newBuy.save(function(err){
  card.buy.addToSet(newBuy._id);
  card.save(function(err,card){
    console.log(card.buy); // card.buy[] has an ObjectId ref & is actually saved to db
  });
});
于 2014-05-29T18:04:35.483 回答