I've got the following MongoDB Schema's
//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],
});
For a particular story the data in MogoDB looks like this:
{
__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!"
}
I'm using Socket.Io to communicate with the server and push the messages to other users
// 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);
});
});
How can i use the above to add the data from socket.io and save it to MogoDB?
socket.room has the same value as sid on Mongo so it finds the correct entry.
socket.username = user
data = text
I've tried to use the below, to save the data but i get an error, i want it to create a new entry in the 'Line' array with the next id.
Story.Lines.User = socket.username;
Story.Lines.text = data;
Story.save();
What method would i use to push this to the db?
* EDIT *
Managed to get it to work, seems like i was using Story rather than story.
Code i used below:
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");
});
});