mongodb / mongoose, how to ensure data is consistent when changing two documents -


lets have mongodb database create document belongs user both documents , users stored in db.

let's further user object contains reference document.

creating new document might looks this.

exports.create = function (req, res, next) {    //make new document   var newdoc = new document({     title: req.body.title,     content: req.body.content,   });   user.findbyid(req.user._id, function (err, user) {     if (err)        return res.send(400);     user.documents.push(newdocument._id);     user.save(function(err){       if (err)          return res.json(400, err);       newdoc.save(function(err) {         if (err)            return res.json(400, err); //<--- if have error here??         return res.json(200, {document:'successfully created'});       });     });   }); }; 

if have error @ last if(err), have added reference new document user document not have been created.

and of course simple case. can more complicated numerous documents referencing each other. cleanest way of handling in mongo/mongoose?

it looks user document relation one-to-many. current operation add new document requires writes 2 collections.

mongodb not provide transactions (maybe in future), option remove document id users documents array, if document save fails. require write may fail.

to more atomic , make done in 1 write, can add userid field document collection , remove decuments array user collection.

also create index on userid in document collection. document references user , creating new document requires 1 write. if write fails nothing changes in database , consistency kept.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -