I need to push multiple values into an array in mongoose using one call. I tried doing it using a smaller array but the array is getting inserted as a sub-array.
var kittySchema = new mongoose.Schema({ name: String, values: [Number] }); var Kitten = db.model('Kitten', kittySchema); Kitten.update({name: 'fluffy'},{$push: {values:[2,3]}},{upsert:true},function(err){ if(err){ console.log(err); }else{ console.log("Successfully added"); } });
The result of the calling the above code thrice gives the below result:
{ "_id" : ObjectId("502b0e807809d79e84403606"), "name" : "fluffy", "values" : [ [ 2, 3 ], [ 2, 3 ], [ 2, 3 ] ] }
Whereas what I want is something like this:
{ "_id" : ObjectId("502b0e807809d79e84403606"), "name" : "fluffy", "values" : [ 2, 3 ,2 ,3, 2, 3] }
Another thing I noticed was that the type in the array (values) is specified as Number, then wouldnt the 'strict' option ensure that anything other than Numbers are not inserted ? In this case another array is being allowed to be inserted.
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
The value of the $in operator is an array that contains few values. The document will be matched where the value of the breed field matches any one of the values inside the array.
Case 1 − Create array with MongoDB. If you want to create an array of field UserName and do not want the field _id, use the below query. If you want to create an array with field name _id only, use the below query.
(Dec-2014 update) Since MongoDB2.4 you should use:
Kitten.update({name: 'fluffy'}, {$push: {values: {$each: [2,3]}}}, {upsert:true}, function(err){ if(err){ console.log(err); }else{ console.log("Successfully added"); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With