node.js - 数组中对象的值在 Mongoose 中不更新
问题描述
我有一个具有以下属性的猫鼬模型:
new Schema({
votes: [{tag: String, votes: Number}]
})
我尝试更改对象内的投票字段,但在调用 .save() 后,该值未更新。我试过使用:
post.markModified('votes')
调用它的代码:
let post = await Post.findById(req.body.postId) //Express request
for(let item in post.votes){ //votes is the array as in the model
if(item.tag === tag){
item.votes += 1
break
}
}
post.save({}, (err, doc) => {
//Other stuff
})
其中 post 是模型,但这也不起作用。更改值后如何保存?
解决方案
好的,我似乎找到了答案,必须使用更新功能:
Post.updateOne({ _id: post.id, 'votes.tag': tag }, { $set: { 'votes.$.votes': 1 } }, (err, raw) => {})
推荐阅读
- html - CSS 强制换行
- swift - 使用 MVVM 架构的 Firestore 分页 swift
- mediawiki - Semantic Mediawiki 和模板中的属性
- java - What is the argument's type for a method that takes indefinite nested arrays?
- java - 在 Gradle 中设置 Groovy AST 转换
- c# - C# 使用或不使用“var”创建一个类的新实例
- reactjs - React map 函数错误,我在哪个地方做错了?
- javascript - 变量未将 Promise 结果存储在节点中
- html - 如何删除标题上方和每一侧的空白空间?
- php - Laravel 8.15.0/Jetstream - 如何注册新刀片 x-jet-newblade?