更新嵌套数组对象(放置请求)

Update nested array object (put request)

我在名为 pown 的集合的文档中有一个数组。

{
    _id: 123..,
    name: pupies,
    pups:[ {name: pup1, location: somewhere}, {name: pup2, ...}]
}

现在使用我的休息服务的用户将整个第一个条目作为放置请求发送:

{name: pup1, location: inTown}

之后我想在我的数据库中更新这个元素。

因此我尝试了这个:

var updatedPup = req.body;
var searchQuery = { 
    _id : 123...,
    pups : { name : req.body.name }
}
var updateQuery = {
    $set: {'pups': updatedPup }
}
db.pown.update(searchQuery, updateQuery, function(err, data){ ... }

不幸的是它没有更新任何东西。 有谁知道如何更新整个数组元素?

正如 Neil 指出的那样,您需要熟悉 dot notation(used to select the fields) and the positional operator $(用于 select 数组中的特定元素,即在原始搜索查询中匹配的元素)。如果要替换数组中的整个元素

var updateQuery= {
      "$set":{"pups.$": updatedPup}
    }

如果只需要更改位置,

var updateQuery= {
  "$set":{"pups.$.location": updatedPup.location}
}

这里的问题是您查询中的 selection 实际上想要更新文档中的嵌入数组元素。第一件事是你想使用 "dot notation" instead, and then you also want the positional $ 修饰符来 select 正确的元素:

db.pown.update(
    { "pups.name": req.body.name },
    { "$set": { "pups.$.locatation": req.body.location } 
)

这将是做事的好方法。主要是因为你真的只想修改子文档的"location" 属性。这就是你表达的方式。