Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

mongoose push doesnt work inside socket.io call

mongoose push doesnt work inside socket.io call

Problem

For some reason, the push to mongodb works with this setup

// Fixed params
story.title = 'Socketi';
story.lines.push ({ author: 'Khuram', text:'socket data'});


//Capture data from socket into schema
 io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });

socket.on('slog', function (data) {

console.log(data);

    });
});

But placing the mongoose push statement within the socket.io call doesnt work

Like so:

// Fixed params
story.title = 'Socketi';



  //Capture data from socket into schema
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });

socket.on('slog', function (data) {

story.lines.push ({ author: 'Khuram', text:data.my});

    });
});

Just for reference purposes: 'slog' refers to the event that i want mongoose to update on. Im receiving data from the client and i want to push the socket event data to mongodb each time this event is emitted (which is why i want to place it within the socket.io call)

Problem courtesy of: Khuram Malik

Solution

Where is your save function executing? I'd recommend putting all your logic for what you want to have happen when you receive a slog message in it's callback and then calling save on instance of story in your callback as well.

Solution courtesy of: Lalit Kapoor

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

mongoose push doesnt work inside socket.io call

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×