0

I'm trying to dynamically generate the $set values to update a users account details in the database. I'm using mongojs. Here is a portion of the code.

var updateData = '';
    if(data.avatar_url) {
        updateData += "avatar_url: \"" + data.avatar_url + "\", ";
    }
    if(data.bio) {
        updateData += "bio: \"" + data.bio + "\", ";
    }
    if(data.chat_background) {
        updateData += "chat_background: \""+ data.chat_background + "\"";
    }
    updateData = "{ " + updateData + " }";
    console.log(updateData);
    db.users.update({ username: socket.username }, {$set: updateData}, function (err, updated) {

For some reason this doesn't work. Any idea why?

Zander17
  • 1,894
  • 5
  • 23
  • 31

1 Answers1

0

Try to pass the data object itself, not the JSON representation of it:

db.users.update({ username: socket.username }, {$set: data}, ...);

Edit:

If data object contains some extra properties, and you don't want them to be inserted into DB, you may try this solution:

var updateData = {
    avatar_url:      data.avatar_url,
    bio:             data.bio,
    chat_background: data.chat_background
};
db.users.update({ username: socket.username }, {$set: updateData}, ...);
Oleg
  • 22,300
  • 9
  • 68
  • 84