【发布时间】:2021-03-04 09:04:29
【问题描述】:
更新查询不会更新特定对象,而是更新与question 匹配且距离数组开头最近的对象,它不采用看起来像的id 参数。
为什么它不起作用?
console.log({id, question, answer, pollId});
Poll.findOneAndUpdate(
{
_id: pollId,
"answers.id": id,
"answers.question": question,
},
{
$set: {
"answers.$.answer": answer,
},
}
).then((p) => console.log(p.answers.filter((a) => a.id === id)[0]));
控制台输出:
//first log
{
id: '603923508d957f957770c64f',
question: 0,
answer: 2,
pollId: '603ca13cd027bd4b3013e9cc'
}
//second log
{
id: '603923508d957f957770c64f',
question: 0,
answer: 0,
pollId: '603ca13cd027bd4b3013e9cc'
}
【问题讨论】:
-
pollId,id和question在第一个和第二个日志中是一样的。 -
是的,我知道,因为我只更新对象的
answer属性。第一个日志是所需的对象,更新后的对象看起来应该是一样的,但事实并非如此。 -
我们可以看一个之前/之后文档的例子吗?
-
如果您使用的是
mongoose库。默认情况下,findOneAndUpdate()返回应用更新之前的文档。设置new: true获取更新数据。例如:findOneAndUpdate(conditions, update, {new: true}) -
与 { new: true } 记录的输出是相同的,遗憾的是。