node.js - 如何从 Socket.IO 向数组 (MongoDB) 添加数据? (node.js)

标签 node.js mongodb express socket.io mongoose

我有以下 MongoDB Schema 的

//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

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

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,
     });

最佳答案

Story.findOne({ sid: socket.room }, function(err, story){
    story.foo = socket.room.foo;
    story.save(function(err, story){
      res.send("Story updated");
    });
});

关于node.js - 如何从 Socket.IO 向数组 (MongoDB) 添加数据? (node.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13001871/

相关文章:

javascript - 有谁知道为什么这个错误在几分钟后一次又一次地发生

javascript - 使用 Nodejs 将图片上传到 MongoDB 并表达

node.js - Nodejs 读取 .xlsx 文件给出奇怪的符号

node.js - Node.js更新文档失败时,最好抛出异常或返回信息吗?

mongodb - Mongo更新所有字段为空的记录

arrays - 我如何从 Mongoose 的数组中找到对象

database - 如何连接到 Oracle Application Express 数据库

node.js - node-sass-middleware 未编译

javascript - 有没有更短的方法来合并重复的对象

node.js - 浏览器 Fetch() API 未将正文发布到后端 Node 服务器