1

我正在尝试通过 socket.io 将变量从服务器传递到客户端。我正在将数据保存到 MongoDB 并使用 Mongoose。目标是将客户端的一些数据保存到数据库中,然后将刚刚保存的文档的 _id 传递回客户端。这是我到目前为止所拥有的:

服务器

client.on('savesnail', function (data) {
    console.log('save snail: ' + data.name);
    var snail = new Snail(data);
    snail.save(function (err, snail) {
        if (err) {console.log('err: ' + err)} // TODO handle the error
        var snailID = snail._id;
        console.log('saved snail ID ' + snailID);
        client.emit('setSnailID', snailID);
        var conditions = {_id: data.ownerID},
            update = {$set: {newUser: false}}

        User.update(conditions,update,function(err){});
        console.log('user updated');
    });

});

客户

saveSnail: function(snail) {
    // Core stats
    var data = {};
    data.ownerID = ig.game.sessionUserID;
    data.inDb = true;
    data.name = snail.name;
    // etc..

    console.log('saving snail');
    this.socket.emit("savesnail", data);
    this.socket.once('setSnailID', function(snailid) {
        snail.snailID = snailid;
        console.log('snail ID set: ' + snailid);
    }); 
}

在服务器控制台中,每个“保存的 snail ID”都应该是唯一且正确的。但是,在它发送到“setSnailID”并且我将相同的变量打印到客户端控制台之后,ID 结果与每次发送都相同。

控制台输出示例

作为一个例子,让我们假设 _ids 是个位数。现在,我在客户端上调用 saveSnail() 四次,为启动的四个蜗牛中的每一个调用一次。在服务器控制台中,我会看到:

saved snail ID 1
saved snail ID 2
saved snail ID 3
saved snail ID 4

...但是当向客户端发送每个 _id 时,在客户端控制台中我看到:

snail ID set: 1
snail ID set: 1
snail ID set: 1
snail ID set: 1

我应该注意,如果我this.socket.once将客户端更改为this.socket.on,客户端控制台会获取每个 ID 的四个实例,因此它开始打印:

snail ID set: 1
snail ID set: 1
snail ID set: 1
snail ID set: 1
snail ID set: 2
snail ID set: 2
snail ID set: 2
snail ID set: 2
// etc

...总共产生 16 行 - 每个 ID 4 行

我最近才开始使用 node.js,并认为我在这里误解了一些非常基本的东西。如何将 MongoDb 分配给每个新条目的正确、唯一的 _id 传递回客户端?

4

1 回答 1

1

Socket.io 不只是发送字符串,它发送几乎任何 javascript 值,包括函数。您可以连同您的数据一起发送回调。

客户:

saveSnail: function(snail) {
    // Core stats
    var data = {};
    data.ownerID = ig.game.sessionUserID;
    data.inDb = true;
    data.name = snail.name;
    // etc..

    console.log('saving snail');
    this.socket.emit("savesnail", data, function (err, snailid) {
      if (err) {
        return console.error(err);
      }
      snail.snailID = snailid;
      console.log('snail ID set: ' + snailid);
    });
}

服务器:

client.on('savesnail', function (data, cb) {
    console.log('save snail: ' + data.name);
    var snail = new Snail(data);
    snail.save(function (err, snail) {
        if (err) {return cb(err);} // Let the client handle the err
        var snailID = snail._id;
        console.log('saved snail ID ' + snailID);
        var conditions = {_id: data.ownerID},
            update = {$set: {newUser: false}}

        User.update(conditions,update,function(err){});
        console.log('user updated');
        cb(null, snailID);
    });
});
于 2013-04-25T23:05:39.193 回答