Search code examples
node.jsmongodbunset

How to set and unset simultaneously in MongoDB from NodeJS?


I have the following code to set data :

MongoClient.connect(mongoConnectionUrl, function (err, db) {
          if (err) {
              console.log("error");
          } else {                  
              var collection = db.collection(collectionName);
              collection.updateOne(query, {
                  "$set": data
              }, function (err) {
                  if (err) {
                      console.log("eror");                          
                  } else {
                    console.log("success.........");                         
                  }
                  db.close();
              });
          }
      });

How can I set data and unset some fields simultaneously?


Solution

  • You can combine $set and $unset operator in the same update operation:

    MongoClient.connect(mongoConnectionUrl, function(err, db) {
      if (err) {
        console.log("error");
      } else {
        var collection = db.collection(collectionName);
        collection.updateOne(query, {
          "$set"  : data,
          "$unset": data,
        }, function(err) {
          if (err) {
            console.log("eror");
          } else {
            console.log("success.........");
          }
          db.close();
        });
      }
    });