gpt4 book ai didi

javascript - Mongoose 嵌套对象不更新

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:31 25 4
gpt4 key购买 nike

摘要

我正在执行 findOneAndUpdate 并尝试更新嵌套对象。我可以找到该文档,但我尝试更新的字段没有更新。我已在下面包含所有相关代码。任何帮助将不胜感激!

Mongoose 模型

const instantCompCompetitors = {
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", require: true },
startingLifeTimeStats: { type: statsFieldsSchema, require: true },
stats: { type: String, require: true },
rank: { type: Number, require: false }
};

const instantCompSchema = mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User", require: true },
compName: { type: String, require: true },
startDate: { type: Date, require: true },
endDate: { type: Date, require: false }, //changed this to false bc we wont have end date when competition starts
inProgress: { type: Boolean, require: true, default: true }, //TODO should I have the default here or just set it to true? Probably easier to have default and then not set it but that seems like may cause errors
competitors: [instantCompCompetitors]
});

findOneAndUpdate

 const updatedComp = await InstantComp.findOneAndUpdate(
{
_id: compId,
"competitors.userId": userObj._id,
inProgress: true
},
{ $set: { "competitors.stats": "testing" } },
{ new: true }
);

错误

MongoError:无法在元素中创建字段“统计信息”

我尝试过的

我尝试将 $set 更改为推送,因为嵌套对象位于数组内,但这也不起作用。

最佳答案

在 @srinivasy 的帮助下我成功解决了这个问题!

解决方案findOneAndUpdate 中的“competitors.stats”应为“competitors.$.stats”。当要更新的元素位于数组内部时,$ 应包含在该元素的路径中。竞争对手是一个数组,这就是为什么 $ 是必要的。

关于javascript - Mongoose 嵌套对象不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57662503/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com