Search code examples
node.jsmongodbatomic

Maintain atomicity in mongodb


I want to maintain atomicity in my mongodb database where if I update a array in my document and if it is successful then the other document would be update else if any document fails then no document should be update.

I am not able to understand how to implement this using mongoClient in my nodejs app.

secureRoutes.post("/sendrequest", function (req, res) {
        MongoClient.connect(url, function (err, db) {
            if (err) throw err;
            else{
            db.collection('users').updateOne({_id:req.user['sub']},{$addToSet:{requested:req.body.id}},function(update1Err,update1Data){
                if (updateErr) throw updateErr;
                else {
                     db.collection('users').updateOne({_id:req.body.id},{$addToSet:{pending:req.user['sub']}});
                }
            });
           
            res.send(JSON.stringify(req.body.id));
            }
        });
        
});

So if first query fails then second would not run and atomicity will be maintained but if first query executes and second fails then the atomicity will not be maintained.

Help me understand the correct implementation. thanks


Solution

  • Check this link for mongodb transaction. I think that's you need.

    https://docs.mongodb.com/manual/core/write-operations-atomicity/