MONGODB猫鼬更新node.js中的嵌入式文档 [英] MONGODB mongoose update embedded document in node.js

查看:88
本文介绍了MONGODB猫鼬更新node.js中的嵌入式文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主文档中有一个嵌入式图像文档,我可以按如下进行更新.每次更新时,它只会覆盖现有图像,而不会将其添加到现有图像中..我尝试使用"{images.push:image}",但这不起作用.语法是什么?我不确定我是否能够解释这个问题.如果没有,请告诉我是否需要在此处添加更多信息.

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

推荐答案

首先尝试对嵌入式文档进行find(),然后将image添加到数组中.

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

这篇关于MONGODB猫鼬更新node.js中的嵌入式文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆