2015-09-27 101 views
1

这里是我的设置:猫鼬不能保存()的调用socket.io

app.js

io.on('connection', function(socket) { 
    socket.on('game-save-comment', function(data) { 
    var result = require('./sockets/games.js')(data); 
    if (result) { socket.emit('comment-ok'); } 
    else { socket.emit('comment-not-ok'); } 
    }); 
}); 

./sockets/games.js

var Game = require('mongoose').model('Game'); 

module.exports = function(data) { 
    var gid = data.gid; 
    var index = data.move; 
    var comment = data.comment; 

    return game = Game.findOne({gid: gid}, function(err, game) { 
     if (!game || err) { 
      return result = false; 
     } else { 
      game.comments[index] = comment; 
      return result = game.save(function(err) { 
       if (err) { 
        return false; 
       } else { 
        return true; 
       } 
      }); 
     } 
    }); 
} 

我想我可能会遇到某种竞赛状况 - 但我不确定。我已将console.log消息放在此代码中的不同位置并触发它。流程进入save()函数并返回true一直到...但是文档从未在数据库中获取更新。

我做错了什么?我想要做的就是更新指定索引处的comments数组。

+0

这解决了我的问题:http://stackoverflow.com/questions/19165571/updating-a-subfield-in-a-mongodb-document - 使用 - findone并节省 – n0pe

回答

2

你没有正确的代码,你需要添加回调到导出的函数参数,并调用一次保存完成回调。类似的东西:

var Game = require('mongoose').model('Game'); 

module.exports = function(data, cb) { 
    var gid = data.gid; 
    var index = data.move; 
    var comment = data.comment; 

    Game.findOne({gid: gid}, function(err, game) { 
     if (!game || err) { 
      cb(err || "Game not found"); 
     } else { 
      game.comments[index] = comment; 
      game.save(cb); 
     } 
    }); 
} 

在这里:

var games = require('./sockets/games.js'); 
games(data, function (err) { 
    if (err) { 
     socket.emit('comment-not-ok'); 
    } else { 
     socket.emit('comment-ok'); 
    } 
});