【问题标题】:Push object to array in mongodb nodejs [closed]将对象推送到mongodb nodejs中的数组[关闭]
【发布时间】:2020-12-20 13:03:37
【问题描述】:

This is my mongodb collection.

我想用 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);
            })

我该怎么做?

【问题讨论】:

  • cmets 数组的外观如何?你的输入result 变量包含什么?请尝试发布文档而不是图片。

标签: javascript node.js arrays mongodb


【解决方案1】:

您可以使用$push 运算符来更新数组。实际上,您也有几种方法可以更新诸如$set 运算符之类的文档,或者找到一个并更改文档然后保存新文档,这将更新您的文档。 此处为 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);
  })

参考资料:

$push

$set

mongoose documents

【讨论】:

  • 欢迎您@AbdiKaan
【解决方案2】:

试试这个:

         url = req.params.posturl
         filter = { url: url }
         Blog.findOne(filter)
            .then((result) => {
               result.like ++;
               return result.save();
            })
            .then(result => {
               res.json({status: 1});
             })
            .catch((error) => {
               console.log(error);
            })

我想你明白了。我不明白 cmets 是什么,但这是你应该尝试的方式

【讨论】:

  • 我的意思是像 youtube cmets。用户登录并进入博客文章。
  • 那么,comment 是博客文章中的嵌套对象,而你有喜欢的评论?
【解决方案3】:

使用 Node.js 驱动程序的 returnOriginal:false 作为数据库调用的第三个参数。将行更改为:

filter = { url: url }
update = { comments: (result.like + 1) }
return = { returnOriginal: false }
Blog.findOneAndUpdate(filter, update, return)

有些人正在使用 Mongoose 来避免这种复杂性。 Node.js 文档很棒,但不那么可读。

【讨论】:

    猜你喜欢
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2019-12-30
    • 2023-01-18
    相关资源
    最近更新 更多