我有以下 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
我尝试使用以下内容来保存数据,但出现错误,我希望它在“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,
});