javascript - Mongoose 嵌套对象不更新

标签 javascript node.js mongodb mongoose

摘要

我正在执行 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/

相关文章:

javascript - 如何在 JSF2 中禁用 .css 和 .js 等静态 Assets 的缓存?

javascript - 在 Electron 应用程序中模拟Ctrl + V

javascript - 不在stream.Readable中实现_read的缺点

json - MongoDB 使用 bson.Raw 从查询中返回整个 JSON

javascript - 如何显示在 iframe 中呈现的 html 文件的源代码

javascript - 反转完整的网页颜色并使用单个切换按钮反转它们

node.js - 从mongoDB删除记录时,elastics不会与其同步

node.js - 类型错误 : Cannot read property 'crud_name' of undefined

javascript - 具有多个值的 Ractive 双向绑定(bind)

javascript - 无法连接到安全 socket.io 服务器 : ERR_SSL_PROTOCOL_ERROR