猫鼬,保存查找结果似乎无能为力

时间:2016-04-03 23:22:50

标签: javascript node.js mongodb mongoose

我有两个架构,FinishedGamePlayingGame。两种模式都是相同的。当我关闭游戏时,我想将PlayingGame复制到FinishedGame集合,然后删除PlayingGame。现在的代码似乎没有抛出错误,但它也没有向FinishedGame添加任何内容。当我打开shell show collections时,我只会看到playinggamessystem.indexes。 非常感谢任何帮助。

下面是我想要关闭游戏时运行的代码:

console.log('finding ', gameId);
PlayingGame.findById(gameId, function(err, game) {
    if (err) {
        console.log(err);
        throw 'Problem finding game when closing';
    }

    console.log(game);
    // if game found, move PlayingGame to FinishedGame emit game closed to room
    if (game) {
        console.log('Saving game to finished games');
        var finishedGame = new FinishedGame(game);
        finishedGame.save(function(err) {
            if (err) throw 'Problem saving finished game when moving playing game to finished game';
            console.log('Successfuly saved to finish game');
            game.remove(function(err) {
                if (err) throw 'Problem removing from playing games';

                socket.leave('game:' + gameId);
                // send message to room that the game has been closed
                io.to('game:' + gameId).emit('game closed');
            });
        });
    }

});

2 个答案:

答案 0 :(得分:0)

您需要在toObject()上调用game,然后再将其传递给FinishedGame构造函数,因为它需要一个普通的JS对象,而不是Mongoose doc实例。

所以将该行更改为:

var finishedGame = new FinishedGame(game.toObject());

答案 1 :(得分:0)

是的,我同意johny的回答。你也可以用 var gameClone = JSON.parse(JSON.stringify(game)); var finishedGame = new FinishedGame(gameClone);