简体   繁体   中英

Mongoose nested object not updating

Summary

I'm doing a findOneAndUpdate and trying to update a nested object. 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

 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

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.

I managed to solve it withs ome help from @srinivasy!

Solution "competitors.stats" in findOneAndUpdate should be "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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