I have the following code:
connection((db) => {
db.collection(\'orders\')
.updateOne(
{ \"_id\": req.body
I had this trouble too, I create a constant with _id from req.body
const {_id} = req.body //pass ID user
await User.updateOne({_id},{$set:data}, (err)=>{
if(err) return res.status(200).json({
error: true,
code: 115,
message: "Erro to update user!"
})
})
Too late but for newbies or students learning nodejs with mongodb. instead of updateOne
method, just use the update
method.
connection((db) => {
db.collection('orders')
.update(
{ "_id": req.body._id}, // Filter
{$set: {"name": req.body.name}}, // Update
{upsert: true} // add document with req.body._id if not exists
)
.then((obj) => {
console.log('Updated - ' + obj);
res.redirect('orders')
})
.catch((err) => {
console.log('Error: ' + err);
}) })
The correct syntax is:
monDb.collection.updateOne(
{"_id": ObjectID(req.params.id)},
{ $set: updateDoc },
function(err, doc) {
...
}
);
Maybe you should use "$set" in your update query like this :
{$set: {"name": req.body.name}}, // Update
More information in documentation
EDIT
If it doesn't work, this is probably because there is no match with your filter.
Maybe you should try to match with an ObjectId like this :
var ObjectID = require('mongodb').ObjectID;
// In your request
{ "_id": ObjectID(req.body._id)}, // Filter
Hope it helps.
Use {$set: {"name": req.body.name}}
(as Sparw mentioned) to update the the properties you want in the document. Also, if the id that you pass as a parameter does not exists in the collection (and you want to create one with the same id) you can pass as a third parameter {upsert: true}
to create one.
In your example:
connection((db) => {
db.collection('orders')
.updateOne(
{ "_id": req.body._id}, // Filter
{$set: {"name": req.body.name}}, // Update
{upsert: true} // add document with req.body._id if not exists
)
.then((obj) => {
console.log('Updated - ' + obj);
res.redirect('orders')
})
.catch((err) => {
console.log('Error: ' + err);
}) })
For me, I have to delete the "_id"/id field before passing the object in the update.
Or it will say that the field is invalid.
Obviously, updated the key while you're using it as a reference isn't the best thing to do.