【问题标题】:MONGODB mongoose update embedded document in node.jsMONGODB mongoose 更新 node.js 中的嵌入文档
【发布时间】:2011-12-04 07:25:57
【问题描述】:

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

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

【问题讨论】:

    标签: mongodb node.js mongoose


    【解决方案1】:

    先尝试find()嵌入文档,然后将image添加到数组中。

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

    【讨论】:

    • 谢谢。这正是我要找的..会试试这个..顺便说一下,我问了一个非常基本的问题,你为什么用“!==”而不是“!=”
    • 它们是严格的“不等于”——但我删除了它们并更改了代码以使其更易于理解;)
    • 你的代码没问题。我认为检查图像“if (item.images && item.images.length).. else {}”可能没有必要。我这样做没有检查图像是否有任何数据。只是在做 item.images.push(image);足够了,它工作正常。
    猜你喜欢
    • 1970-01-01
    • 2014-06-12
    • 2023-03-10
    • 1970-01-01
    • 2011-12-21
    • 1970-01-01
    • 2012-11-20
    • 2021-03-26
    相关资源
    最近更新 更多