Expressjs&集合中的MongoDB更新对象's数组

Expressjs & MongoDB update object in collection's array

本文关键字:对象 更新 数组 amp 集合 Expressjs MongoDB      更新时间:2023-09-26

我想更新集合的数组,我在集合的数组中查找对象和向对象推送新值时遇到了问题,我尝试了一些事情,但后来似乎无法在数组上使用集合方法?

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中,我有数组功能,我想在该数组上查找方法,并根据id查找对象,然后在可能的情况下进行推送。

实际上如何找到数组?因此可以在该数组上执行一些操作,如查找和更新。我现在这个表达式的特点是:[]看起来不正确,但我不知道如何找到它。

我试过这种

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

如果集合有一个具有数组功能的文档?它不应该起作用吗?

在mongodb中,我发现了

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

所以它应该研究集合的特性,并给出所有对象的结果——哪个属性是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中使用Arrays方面,要将项添加到要使用$push的数组中,并从数组中删除项,需要使用$pull

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