.updateOne on MongoDB not working in Node.js

后端 未结 8 1041
迷失自我
迷失自我 2021-01-03 20:07

I have the following code:

connection((db) => {
            db.collection(\'orders\')
                .updateOne(
                    { \"_id\": req.body         


        
8条回答
  •  天涯浪人
    2021-01-03 20:44

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

提交回复
热议问题