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

Viewed 59318

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.

4 Answers

Currently, the updated doc doesn't support $pushAll. It seems to have been deprecated. Now the good choice is to use the combination of $push & $each

an example:

//User schema: {uid: String, transaction: [objects] }
const filter = {"uid": uid};
const update = {
        $push: {
            transactions: {$each: dataarr}
        }
    }
User.updateOne(filter, update, {upsert:true}, (err) => {
        if(err){
            console.log(err)
        }
    })

pass {upsert: true} at options to insert if the filter returns false.

Related