Node.js 数组中对象的值在Mongoose中不更新
我有一个猫鼬模型,具有以下属性:Node.js 数组中对象的值在Mongoose中不更新,node.js,mongodb,mongoose,mongoose-schema,Node.js,Mongodb,Mongoose,Mongoose Schema,我有一个猫鼬模型,具有以下属性: 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){ //vo
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是模型,但这也不起作用。更改值后如何保存?。save()
不会更新数组
您必须使用查询更新数组
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
}
}
// update the votes aray with the modified votes array:
Post.findByIdAndUpdate(req.body.postId, {votes: votes}, (err, doc => {
// do your stuff
}))
试试这段代码,它的逻辑与上面使用的相同,通过
ID
查找博客文章,并检查对象投票中名为tag
的does字段,如果是,则将字段likes
值增加+1
express.method("/:postId", async (req, res) => {
try {
const updatedBlog = await Post.findOneAndUpdate(
{
_id: req.body.postId,
"votes.tag": { $exists: true }
},
{
$inc: { "item.votes": 1 }
},
{ new: true } //to return the new document
);
res.json(updatedBlog);
} catch (error) {
res.status(400).end();
}
});
好的,我似乎已经找到了答案,必须使用更新功能:
Post.updateOne({ _id: post.id, 'votes.tag': tag }, { $set: { 'votes.$.votes': 1 } }, (err, raw) => {})
你能给我们提供你试图«更改对象内投票字段»的代码吗?@Alexedim在问题中添加了它,如果(item.tag==tag)
你确定等式真的相等吗?我的意思是,如果是这样的话,那你为什么要打破这个声明呢?当然,它不会触发.save()
,而且,尝试.save()
它,而不回调。他处理的是对象
而不是数组
,看看for(让对象中的项)
它不是for(让数组中的项)
是的,我知道。这将更新整个阵列。另外,我尝试不使用mongoose查询,因为他必须更改所有api。同样在您的回答中,将response.json
更改为res.json
,因为您正在异步函数中使用res
。