Ajax jQuery
Ajax jQuery

Reputation: 345

How to add new items to an array in MongoDB

I'm trying to add a new item to whichever name that was passed in under whichever id. My first problem is that it seems like its not grabbing the values from any of my variables (name, item, id), instead just using them as object keys. My next issue is that when I tested by hard-coding sample table info onto here, it wasn't adding more items to that array, but simply replacing the entire array with whatever values I had here.

function addlist(name, item, id){ // Add to user's list
    console.log(id);
    db.collection('newcon').update({_id: id}, { "$set": { "$push": { name:item } } });
    ret(id);    
}

Upvotes: 0

Views: 111

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

$set is not an array update operation.

The $set operator replaces the value of a field with the specified value.

You just want to use $push by itself, as in

.update({_id: id}, {$push: {name: item}})

You can't interpolate object property names in raw object declarations, so if you want to use a variable name you will have to create an object to do this:

var obj = {};
obj[name] = item;

You can then pass this to .update, {$push: obj}

Upvotes: 2

Related Questions