我想使用findOneAndUpdate()将对象推送到数组。
这是我的nodejs代码。
url = req.params.posturl
filter = { url: url }
update = { comments: (result.like + 1) }
// maybe you can try save/get this to/in .json
Blog.findOneAndUpdate(filter, update)
.then((result) => {
res.json({ status: 1 })
})
.catch((error) => {
console.log(error);
})
我怎样才能做到这一点?
您可以使用$push
运算符来更新数组。实际上,您也可以通过几种方式来更新文档,例如$set
operator,或者找到一个并更改文档然后保存新文档,这将更新您的文档。TLDR代码在这里;
const url = req.params.posturl
const newComment = req.body.comment
const filter = { url }
const willBePush = { comments: newComment }
Blog.findOneAndUpdate(filter, { $push: willBePush })
.then((result) => {
/** Do whatever with response if you want to see new document you can pass { new: true } as option for findOneAndUpdate method*/
console.log(result)
})
.catch((error) => {
console.log(error);
})
参考文献:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句