Mohanraj
Mohanraj

Reputation: 19

data can't be updated in mongodb

This error appears in my node js console:

(node:6048) UnhandledPromiseRejectionWarning: MongoError: document must be a valid JavaScript object

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!",
        })
    }
    );

Upvotes: 0

Views: 539

Answers (2)

Sanaullah
Sanaullah

Reputation: 374

I think you were not passing the condition that where you want the update like add name=mohan .

Use cors for cross origin request and body parser for parse the form data

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!",
                })
            }
            );

Upvotes: 0

Malik Awan
Malik Awan

Reputation: 463

updateOne() has first parameter as filter. Define your filter and then update.

//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();
                });
              });

Upvotes: 1

Related Questions