Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push an array of objects into an array in mongoose with one call?

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.

like image 506
Pranil Dasika Avatar asked Aug 15 '12 03:08

Pranil Dasika


People also ask

How do I push an array into an array in MongoDB?

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.

What is $in in mongoose?

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.

How do I create an array in MongoDB query?

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.


1 Answers

(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");         } }); 
like image 65
Amit Portnoy Avatar answered Sep 21 '22 09:09

Amit Portnoy