我来自关系数据库,而主键(本例中为 _id)在其生命周期中是相同的,因此当我在 mongodb 中看到这种行为时,我感到很惊讶。
我按以下方式使用猫鼬的 findOneAndUpdate 插件方法:
User.findOneAndUpdate(
{ "products._id": _id, "_id": req.payload._id },
{
$set: {
"products.$": { name: "New name" },
},
},
{
new: true,
runValidators: true,
},
function (err, doc) {
if (err != null) {
res
.status(500)
.json({
message: "Error on updating. Please, try again later.",
});
} else if (doc == null) {
res.status(404).json({ message: "Product not found." });
} else {
res.status(200).json(doc.products);
}
}
);
Run Code Online (Sandbox Code Playgroud)
开始之前:
{_id: 58b5e637f9f904a800721abf, name: "Old name"}
Run Code Online (Sandbox Code Playgroud)
(_id 更改) …