【问题标题】:How to add data to an array (MongoDB) from Socket.IO? (node.js)如何从 Socket.IO 向数组 (MongoDB) 添加数据? (node.js)
【发布时间】:2012-10-11 16:45:50
【问题描述】:

我有以下 MongoDB 架构

//MongoDB Schema    

var Line = new Schema({
    id    : Number,
    user  : String,
    text  : String,
});


var Story = new Schema ({
    sid: {type: String, unique: true, required: true},
    maxlines: {type: Number, default: 10}, // Max number of lines per user
    title: {type: String, default: 'Select here to set a title'},
    lines: [Line],
});

对于特定的故事,MogoDB 中的数据如下所示:

{
__v: 0,
_id: ObjectId("5084559945a0a23c1b000002"),
lines: [{
        "id": 1,
        "user": "Joe",
        "text": "This is line number 1"
    },
    {
        "id": 2,
        "user": "Adam",
        "text": "This is line number 2"
    },
    {
        "id": 3,
        "user": "John",
        "text": "This is line number 3"
    },
],
maxlines: 10,
sid: "lJOezsysf",
title: "A New Story!"
}

我正在使用 Socket.Io 与服务器通信并将消息推送给其他用户

// when the client emits 'sendline', this listens and executes
    socket.on('sendline', function (data) {
        // we tell the client to execute 'updatestory' with 2 parameters
        io.sockets.in(socket.room).emit('updatestory', socket.username, data);  
        Story.findOne({ sid: socket.room }, function(err, story){

           **    What would go here to update MongoDB? **

            console.log(socket.room);
        });
    });

如何使用上面的方法从 socket.io 添加数据并将其保存到 MogoDB?

socket.room has the same value as sid on Mongo so it finds the correct entry.
socket.username = user
data = text

我尝试使用以下方法来保存数据,但出现错误,我希望它在“Line”数组中创建一个具有下一个 id 的新条目。

Story.Lines.User = socket.username;
Story.Lines.text = data;
Story.save();

我将使用什么方法将其推送到数据库?

* 编辑 *

设法让它工作,好像我使用的是故事而不是故事。

我在下面使用的代码:

    Story.findOne({ sid: socket.room }, function(err, story){   
    story.lines.push({ 
    user: socket.username, 
    text: data,
     });

【问题讨论】:

  • 我得到:'\node_modules\mongoose\lib\utils.js:413,抛出错误; TypeError: Cannot set property 'User' of undefined' 然后应用程序就停止了
  • 我也试过Story.lines.push({ user: socket.username, text: data.my, }); Story.save(); 给我一个错误“TypeError: Cannot call method 'push' of undefined

标签: node.js mongodb express socket.io mongoose


【解决方案1】:
Story.findOne({ sid: socket.room }, function(err, story){
    story.foo = socket.room.foo;
    story.save(function(err, story){
      res.send("Story updated");
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-02
    • 2021-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多