猫鼬嵌套对象不更新

时间:2019-08-26 17:39:38

标签: javascript node.js mongodb mongoose

摘要

我正在执行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:无法在元素中创建字段“统计信息”

我尝试过的事情

我尝试将$ set更改为push,因为嵌套对象位于数组内部,但是也无法正常工作。

1 个答案:

答案 0 :(得分:0)

我在@srinivasy的一些帮助下设法解决了这个问题!

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