Vladimir
Vladimir

Reputation: 1789

How to push array of objects on update mongoose

I tried something like this:

query:

query = {
      pictures: {$pushAll: files}
}

files array look like this:

[{ fieldname: 'productPhotos',
        originalname: 'images.jpg',
        encoding: '7bit',
        mimetype: 'image/jpeg',
        filename: '422e64cfb147eff02fee5166d63939b10564d4ad-images.jpg',
        }]

Update mongoose model:

 Product.update({ _id: product.productId}, query,...

Model look like this for pictures:

pictures: [{
        filename: {
            type: String,
            required: false
        }
    }],

Problem is array in database not update... Any solution?

Upvotes: 0

Views: 2615

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151102

Wrong way around, and you should use $push and $each. i.e

Product.update(
 { "_id": product.productId }, 
 { "$push": { "pictures": { "$each": files } } },
 function(err,callback) {

 }
) 

So the update operator ( i.e $push ) is at the root of the update statement followed by the field(s) to apply to.$each is a modifier to accept a "list" if content to add as opposed to "singular"

Upvotes: 4

Related Questions