Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have the following code:

connection((db) => { 

db.collection('orders') 

.updateOne( 

{ "_id": req.body._id}, // Filter 

{"name": req.body.name} // Update 

)

 .then((obj) => { 

console.log('Updated - ' + obj); 

res.redirect('orders') 

}) 

.catch((err) => { 

console.log('Error: ' + err); 

}) 

})

I want to change the name in the order but it doesn't update it. The result in the console is

Updated - {"n":0,"nModified":0,"ok":1}

I tried to read the documentation but it's horrific

2 Answers

0 votes
by (106k points)

To update MongoDB you should use "$set" in your update query like as follows:-

{$set: {"name": req.body.name}}, 

+1 vote
by (107k points)

If the above answer doesn't work, this is probably because there is no match with your filter.

You should try to match an ObjectId like the following:

var ObjectID = require('mongodb').ObjectID;

// In your request

{ "_id": ObjectID(req.body._id)}, // Filter

I hope it helps.

.updateOne on MongoDB not working in Node.js
Intellipaat-community
by
reshown by
Perfect! This was it. Thanks vinita.

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...