简体   繁体   English

猫鼬嵌套对象不更新

[英]Mongoose nested object not updating

Summary 摘要

I'm doing a findOneAndUpdate and trying to update a nested object. 我正在执行findOneAndUpdate并尝试更新嵌套对象。 I can find the document but the field I'm trying to update is not being updated. 我可以找到该文档,但是我要更新的字段没有被更新。 I've included all of the relevant code below. 我已经在下面包含了所有相关代码。 Any help would be greatly appreciated! 任何帮助将不胜感激!

Mongoose Model 猫鼬模型

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 findOneAndUpdate

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

Error 错误

MongoError: Cannot create field 'stats' in element MongoError:无法在元素中创建字段“ stats”

What I've tried 我尝试过的

I've tried changing $set to push since the nested object is inside an array however that is also not working. 我试过更改$ set进行推送,因为嵌套对象位于数组内部,但是这也不起作用。

I managed to solve it withs ome help from @srinivasy! 我设法通过@srinivasy的一些帮助解决了它!

Solution "competitors.stats" in findOneAndUpdate should be "competitors.$.stats". findOneAndUpdate中的解决方案 “ competitors.stats”应为“ competitors。$。stats”。 The $ should be included in the path for the element you want to update when that element is inside of an array. 当该元素位于数组中时,$应该包含在要更新的元素的路径中。 Competitors is an array which is why $ is necessary. 竞争对手是一个数组,这就是为什么$是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM