猫鼬找到最新的条目

时间:2013-02-23 16:57:39

标签: node.js socket.io mongoose

我有一个如下所示的条目:

{
  "__v": 10,
  "_id": "50f8050ed714645500000002",
  "sid": "DI7gZ0sprJ",
  "lines": [
    {
      "text": "Well that's what some people say anyway",
      "_id": "50f80526d714645500000003",
      "user": "Player456"
    },
    {
      "text": "They're people just like the rest of us",
      "_id": "50f805925543712caf000005",
      "user": "Player123"
    },
  ],
  "title": "Test",
  "maxlines": 0
}

并有一个socket.io脚本,如下所示:

socket.on('sendchat', function (data) {
    Story.findOne({ sid: socket.room }, function(err, story){
        if (err) {
            console.log(err);
        }
        else if(story == null) {
            console.log(err);
        }
        else {
            io.sockets.in(socket.room).emit('updatechat', socket.username, data);
            story.maxlines = story.maxlines - 1;

            if (story.maxlines == 0) {
                // End Game Script - Redirect to view page
                io.sockets.in(socket.room).emit('gameover', slugs(story.title), socket.room);
            }
            //Save Story to DB
            story.lines.push({
                user: socket.username,
                text: data
            });
            story.save(function(err, story){
                if (err) {
                    console.log(err);
                }
                else {
                    console.log("Story Updated");
                }
            });
        };
    });
});

有没有办法可以查看socket.username是否等于最新一行输入的用户?

例如,上面的Player123是最后一个输入一行,所以如果Player123再次尝试它只是发出一个错误,但如果Player456进入一行,那么Player123能够再次

我正在尝试创建一个简单的回合制游戏,该游戏会检查以确保一个人在轮到他们时不能进入该行

1 个答案:

答案 0 :(得分:1)

您可以直接检查lines对象中story数组中的最后一个条目。如:

if (story.lines.length &&
    story.lines[story.lines.length-1].user === socket.username) {
    // error, same user is trying to enter another line
}