mongodb中无法更新数据

时间:2019-07-16 07:24:11

标签: node.js reactjs mongodb

此错误出现在我的节点js控制台中:

  

(节点:6048)UnhandledPromiseRejectionWarning:MongoError:文档必须是有效的JavaScript对象

router.post('/datapassfup', (req, res) => {
        console.log("submitted values are",req.body)
        MongoClient.connect(url, function(err, db) {
            if (err) throw err;
            var dbo = db.db("mohan");
            var myobj =req.body;
            dbo.collection("customers").updateOne({$set:{myobj}}, function(err, res) {
              if (err) throw err;
              //console.log("1 document inserted");
              db.close();
            });
          });
        res.json({
            statusCode: 200,
            result: "hi how are you!",
        })
    }
    );

2 个答案:

答案 0 :(得分:0)

updateOne()具有第一个参数作为过滤器。定义您的过滤器,然后更新。

//suppose you are getting id in order to update
    let userId = req.body.updatedUser.id;
    let userName = req.body.updatedUser.username;
    let name = req.body.updatedUser.name;
    dbo.collection("customers").updateOne({_id: userId},{$set:{name, username:userName}}, 
    function(err, res) {
                  if (err) throw err;
                  //console.log("1 document inserted");
                  db.close();
                });
              });

答案 1 :(得分:0)

我认为您没有通过条件,例如add name = mohan。使用cors进行跨源请求,使用正文解析器解析表单数据

const cors = require("cors");
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser());
app.use(bodyParser.urlencoded());
app.use(cors());
var MongoClient = require('mongodb').MongoClient;
//url like var url = "mongodb://localhost:27017"
     router.post('/datapassfup', (req, res) => {
                console.log("submitted values are",req.body)
                MongoClient.connect(url, function(err, db) {
                    if (err) throw err;
                    var dbo = db.db("mohan");
                    var myobj =req.body;
                    dbo.collection("customers").updateOne({name:"mohan"},{$set:{myobj}}, function(err, res) {
                      if (err) throw err;
                      //console.log("1 document inserted");
                      db.close();
                    });
                  });
                res.json({
                    statusCode: 200,
                    result: "hi how are you!",
                })
            }
            );