开发者

MONGODB mongoose update embedded document in node.js

I have an embedded image document in my main document and I am able to update it as follows. Everytime it updates, it just overrides the existing image and does not add it to the existing images.. I tried by "{images.push: image}", but that does not work. what is the syntax ? I am not sure if i am able to explain the problem. if not, please let me know if i need to add more info here.

var image = {
                    img     : new_file_name,
                    orig_img_name   : files.source.filename,
                    caption : fields.message,
                    upload_date : new Date()
                };

RentModel.update({'facebook_id':fb_id, 'prop_location.lat':lat, 'prop_location.lng':lng},   {'images':image}, function(err, docs){
                        if(err) {
                            console.log("Error during friends update");
                            throw err;
                        }
                        console.log('image updated to database', new_file_n开发者_如何学运维ame);
                    });


try to find() the embedded document first and then add the image to the array.

RentModel.find({'facebook_id':fb_id, 'prop_location.lat':lat, 'prop_location.lng':lng}, function (err, item) {
    if (err) //throw ...
    if (item) {
      if (item.images && item.images.length) {
          item.images.push(image);
      }
      else {
          item.images = [image];
      }

      // save changes
      item.save(function (err) {
         if (!err) {
             // done ...
         }
      });
    }
}); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜