[英]Mongoose nested object not updating
摘要
我正在执行findOneAndUpdate并尝试更新嵌套对象。 我可以找到该文档,但是我要更新的字段没有被更新。 我已经在下面包含了所有相关代码。 任何帮助将不胜感激!
猫鼬模型
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:无法在元素中创建字段“ stats”
我尝试过的
我试过更改$ set进行推送,因为嵌套对象位于数组内部,但是这也不起作用。
我设法通过@srinivasy的一些帮助解决了它!
findOneAndUpdate中的解决方案 “ competitors.stats”应为“ competitors。$。stats”。 当该元素位于数组中时,$应该包含在要更新的元素的路径中。 竞争对手是一个数组,这就是为什么$是必需的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.