【问题标题】:How to get return value from Mongoose save function using axios in React JS?如何在 React JS 中使用 axios 从 Mongoose 保存函数中获取返回值?
【发布时间】:2021-01-21 09:31:26
【问题描述】:

我是 React JS 的新手,我创建了一个简单的应用程序,它接受用户名和电子邮件并插入到 MongoDB。

我使用React + Node + Express + Mongoose + MongoDB 并且能够成功插入记录

DB.js

router.route("/insert").post(function(req, res) {

  let comments = new Comments(req.body);
  console.log(req.body)
  comments.save();
});

App.js

axios.post("http://localhost:4000/insert", {
            UserName:  username,
            UserEmail: email,
            Comments:  comments
        })

现在,我想将 'numRowsAffected'DB.js 返回到 App.js

因此,我修改了 DB.js,为 mongoose save() 函数添加了回调

router.route("/insert").post(function(req, res) {
  let comments = new Comments(req.body);
  console.log(req.body)
  comments.save(function(err, comments, numRows) {
      if ( err ) { 
          res.send(err);
      }
      else {
          res.json({ message: 'Comments added', data: numRows });
      }
  });
});

但是,我不知道如何更改 App.js (ie in axios.post) 上的代码以从 DB.js

获取返回值

非常感谢任何帮助

【问题讨论】:

    标签: reactjs mongoose axios mern


    【解决方案1】:

    您可以使用Mongoose.update() 并将upsert 选项设置为true 而不是Mongoose.save() 并读取updatenModifiednInserted 属性返回值。

    您可以查看this的帖子了解更多详情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 2014-04-05
      • 2020-08-21
      • 2011-08-27
      相关资源
      最近更新 更多