次の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
以下を使用してデータを保存しようとしましたが、エラーが発生しました。次の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,
});