【发布时间】:2020-08-08 15:52:30
【问题描述】:
我正在尝试更新文档中的对象
文档:猫
{
"_id": "5e5cb512e90bd40017385305",
"type": "cat"
"history": [
{
"id": "randomID",
"content": "xyz",
},
{
"id": "randomID2",
"content": "abc",
}
]
}
选择和更新历史数组中的对象的代码:
const editHistory = async (_, { input }, ctx) => {
let query = { _id: input.catId, "history.id": input.historyId };
let update = { $set: { "history.$": input.history } };
let options = {
new: true,
fields: { history: { $elemMatch: { id: "randomID" } } }
};
let cat = await ctx.models.cats.findOneAndUpdate(query, update, options);
return cat;
};
输入有以下值
input: {
catId: "5e5cb512e90bd40017385305",
historyId: "randomID",
history: {
id: "randomID",
content: "new content"
}}
我尝试使用 Projection,我使用 select 将其更改为字段,可在 mongoose 文档中找到。 我仍然无法更新这些值。我查询或选择子字段的方式有什么问题吗?
【问题讨论】:
-
id(文档)或_id(查询)? -
Cat 文档的 _id 和历史数组对象的 id
-
当您使用相同的查询运行
findOne时会发生什么? -
它只是返回 Cat 文档
-
@mickl 有办法解决这个问题吗?
标签: database mongodb mongoose mongodb-query mongoose-schema