Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

How do I access properties on this object?

I am working in node.js and socket.io, basically I listen for a socket disconnect event and call a method. app.update()

socket.on('disconnect', function (data) {
    app.update();
});

// This is in another file, and the id is static, but I am more concered with the
// messages object that is passed through.
update: function() {
    models.Message.find({_id: "532c8d9ce889ed4c21538630"}, function(err, messages) {
        console.log(messages)
    });
}

This is what the messages object looks like

[ { username: 'Marcus',                                         
    connected: true,                                            
    _id: 532c8d9ce889ed4c21538630,                              
    __v: 0 } ]

I am not sure how to access an object with the brackets around it, but basically I want to update the object so that I can set connected to false.

I tried messages['connected'].

Upvotes: 1

Views: 55

Answers (3)

Scott Sauyet
Scott Sauyet

Reputation: 50787

If you want to update each one of them:

messages.forEach(function(message) {
    message.connected = false;
});

Upvotes: 0

martskins
martskins

Reputation: 2940

messages may contain more than one result, so you have an array there.

Actually messages will always be an array because you're using find, which expects multiple results. If you used findOne instead it wouldn't be an array but a document.

You should try for example.. messages[0].username

Upvotes: 3

GrimFere
GrimFere

Reputation: 141

You've got an array of objects. So you need to access the first element of the array, and then the 'connected' property. Do this:

messages[0].connected = false;

Upvotes: 3

Related Questions