javascript - Expressjs 和 MongoDB 更新集合数组中的对象

标签 javascript mongodb express

我想更新集合的数组,我在查找集合的数组中的对象并将新值推送到对象时遇到问题,我尝试了一些东西,但似乎我无法在数组上使用集合方法?

router.post('/mountain_rescue_update', function(req, res) {
  var collection = db.collection('rescuemodels');
  var id = req.body.id;

  collection.update({"type": "FeatureCollection"},function (err, doc) {
     if (doc) {
         doc.find({"features": []}, function (err, result) {
             if (err) throw err;

             res.send(result);
         });
     }
   });
    }); 

在FeatureCollection中,我有数组特征,我想在该数组上执行find方法并通过id查找对象,然后如果可能的话进行推送。

实际上如何查找数组?因此可以在该数组上完成一些操作,例如查找和更新。我现在表达式 features: [] 看起来不正确,但我不知道如何找到它。

我尝试过这样的事情

collection.find({"features":{"properties":{"date":id}}}, function(err,doc){
     console.log(doc);
  }

集合中是否有一个具有数组特性的文档?不应该起作用吗?

在mongodb中我发现

       db.rescuemodels.find({"features.properties":{"title":"Wild Wolfs"}})

所以它应该研究集合特征并给出properties.title是Wild Wolfs的所有对象的结果?

我的json

{
  "_id" : ObjectId("54f50753a879d4e045b24878"),
  "features" : [
     {
         "properties" : {
             "title" : "Alona 45D",
             "description" : "...",
             "date" : ISODate("2015-03-03T01:00:40.842Z"),
             "urgency" : "Low",
             "phone" : "675 675 345",
             "completion" : "NO",
             "rescuer" : "Aleksander Gagarin"
             },
         "geometry" : {
             "coordinates" : [
                 11.2637333,
                 23.1135565
                 ],
             "type" : "Point"
           },
        "type" : "Feature"
        },...etc

      ],
  "type" : "FeatureCollection",
    "__v" : 0
   }

好吧,我成功地在文档数组中找到了对象,所以现在只需替换​​剩下的一些属性。

 db.rescuemodels.find({"type":"FeatureCollection"},{"features": {$elemMatch:{"properties.title":"W"}}})

也许有人知道如何表达这个声明

   db.rescuemodels.update({"type":"FeatureCollection"},{"features":{$elemMatch:{"properties.title":"W"}}},{$set:{"features":{"properties":{"title":"XXX"}}}})

最佳答案

您可能想要使用 findOneByIdAndUpdate。就在 mongodb 中使用数组而言,要将项目添加到数组中,您需要使用 $push 并从数组中删除项目,您需要使用 $pull。强>

http://docs.mongodb.org/manual/reference/operator/update/push/

关于javascript - Expressjs 和 MongoDB 更新集合数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28836674/

相关文章:

javascript - MongoDB - 使用范围查询进行分页

javascript - $rootScope.digest 没有完成 Jasmine 中的 promise

javascript - 片段 : Detect if a snippet prefix is used in a string or regular javascript

python - Django 是否允许为 MongoDB 中的每个文档定义不同的字段集?

java - 从JAVA连接MongoDB的问题

node.js - jade 中变量内的长字符串

javascript - 无法正确更新 Ajax 响应上的 Flot 图

c# - 验证客户端下拉列表中选定月份和年份的选定日期

node.js - 仅在 NodeJs 上构建网站,并且 Express 阻止通过 http 的请求

javascript - WebStorm 6 无法识别 Node.js Express 发布方法