简体   繁体   中英

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_name);
                    });

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 ...
         }
      });
    }
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM