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