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 ...
}
});
}
});
精彩评论