我在使用mongoose将一些数据保存到Mongo时遇到了问题。
在我的数据库模块中,我正在做:
self.addMove = function (gameId, move, callback) {
Game.findById(gameId, function (err, game) {
if (err)
callback(err);
else {
game.newMove = move; //apply new move
game.save(Game.transformState(callback)); //save the game
}
});
};
其中newMove在GameSchema中被定义为虚拟方法
GameSchema.virtual('newMove').set(function (move) {
if (move.player !== move.piece[0])
return;
if (allowedMove(move)) { //if piece is allowed to move
var from = positionToIndex(move.from),
to = positionToIndex(move.to);
this._field[to] = this._field[from]; //move it
this._field[from] = "";
}
});
和transformState作为静态方法
GameSchema.statics.transformState = function (callback) {
return function (err, data) {
if (err)
callback(err);
else
callback(null, {
_id: data._id,
moves: data.moves,
field: data.field //data.field transforms 1D array into 2D client-useable array
});
};
};
我如何调用addMove:
socket.on('addMove', function (msg) {
console.log('New move: ' + msg);
var msg = JSON.parse(msg);
db.addMove(msg._id, msg.move, function (err, data) {
if(!err)
io.emit('getState', JSON.stringify(data));
});
});
根据要求,我的GameSchema:
GameSchema = new Schema({
moves: [MoveSchema],
_field: {
type: [String],
default: ["WR", "WN", "WB", "WQ", "WK", "WB", "WN", "WR", "WP", "WP", "WP", "WP", "WP", "WP", "WP", "WP", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "BP", "BP", "BP", "BP", "BP", "BP", "BP", "BP", "BR", "BN", "BB", "BQ", "BK", "BB", "BN", "BR"]
}
})
作为奖励,这是我第二次请求游戏状态的方式:
//sockets.js
socket.on('getState', function (msg) {
console.log('User requested game state!');
var msg = JSON.parse(msg);
db.getGame(msg._id, function (err, data) {
if(!err)
io.emit('getState', JSON.stringify(data));
});
});
//database.js
self.getGame = function (id, callback) {
Game.findById(id, Game.transformState(callback));
};
正如您所看到的,每当我从客户端获得新动作时,我都会修改当前游戏区域并保存该游戏。当我用game.save(Game.transformState(callback));
保存它时,它已被保存了#34;这意味着回调中的数据是正确的。但如果我再次尝试请求游戏状态,我可以看到它没有被保存。我也尝试手动检查MongoDB,但确实没有保存。我试图解释的是,在行game.save(Game.transformState(callback));
中,函数callback
以更新的游戏状态执行,我可以在客户端看到它,但状态实际上没有保存在数据库中。
答案 0 :(得分:2)
显然,如果直接修改数组,mongoose不会检测字段是否已更改。为了触发检测,我使用了this.markModified('_field');
我还发现了一些其他的方法: Mongoose: assign field of type 'array of Strings'