【问题标题】:Mongoose populate losing array saved changesMongoose 填充丢失的数组保存的更改
【发布时间】:2014-06-19 10:30:09
【问题描述】:

在保存后填充时,我丢失了对 Mongoose 模型的一些(但不是全部)更改。我从一个数组中拼接出一个随机(这里简化为第一个)元素并将其分配给另一个变量。目标(activeTile)和数组(unusedTiles)都在数据库中更新,但在填充调用中,我只看到目标的更新,而不是数组的更新。

// Executing code
console.log('==0> ' + gamestate.unusedTiles.length);
console.log('==0> ' + gamestate.activeTile.tile);
gamestate.nextTile(function(err, gamestate2) {
    console.log('==2>' + gamestate2.unusedTiles.length);
    console.log('==2>' + gamestate2.activeTile);
    gamestate2.populate('activeTile unusedTiles', function(err, gamestate3) {
        console.log('==3> ' + gamestate3.unusedTiles.length);
        console.log('==3> ' + gamestate3.activeTile);
    });
});

// And in the Mongoose model
var gamestateSchema = mongoose.Schema({
    unusedTiles: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Tile' }],
    activeTile: { type: mongoose.Schema.Types.ObjectId, ref: 'Tile' }
});

gamestateSchema.methods.nextTile = function(callback) { 
    var gamestate = this;
    gamestate.activeTile = gamestate.unusedTiles.splice(0, 1)[0];           
    gamestate.markModified('unusedTiles');
    gamestate.save(function(err, gamestate1) {
        console.log('==1> ' + gamestate1.unusedTiles.length);
        console.log('==1> ' + gamestate1.activeTile);
        callback(err, gamestate1);
    });        
}

生成的控制台输出如下所示:

==0> 65
==0> 5356b8907b915c0000e068a2
==1> 64
==1> 5356b8907b915c0000e06887
==2> 64
==2> 5356b8907b915c0000e06887
==3> 65
==3> {
       _id: 5356b8907b915c0000e06887,
       ... // rest of tile object
     }

我希望在填充回调中可以看到这两种变化。所以未使用的Tiles 数组的新长度应该是 65 而不是 64。知道发生了什么吗?

我正在使用 Mongoose 3.8.1。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    看起来我需要在填充之前再次将数组标记为已修改。我猜猫鼬会从数据库中取出旧数组以进行填充?这没有多大意义,因为填充是在保存回调中完成的。不确定,但它正在适应这种变化。

    gamestate2.markModified('unusedTiles');
    

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2019-01-31
      • 2014-12-05
      • 2021-11-17
      • 1970-01-01
      • 2019-07-28
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      相关资源
      最近更新 更多