node.js - How to use mongoose to save multiple documents? -


i have 2 models here user , blog. when user write blog, router invoke them this.

promise.all([                     node.save(),                     user.save()                 ]).then(function (values) {                                         //do                 }).catch(function (err) {                     //print error                 }) 

as may notice immediately, there's no guarantee save(). either of them fails , no rollback rest. how can make sure both of them saved or rollbacked? people suggest put blogs collection inside users in single document, that's hard blog ranking, isn't it? i'm not sure if it's practice putting things in mongodb. if documents large, cause performance issues(say requests/second)?

thanks.

you can't use promise.all, you'll have chain promises individually.

node.save().then(user.save).then(function(){//do else}); 

you'll have work little harder entities in array promise.all. need that? have access user , node entities already.

the classic way using async , series:

async.series({       node: node.save,      user:user.save }, function(err, res){         // res equal to: {node:node, user:user}    }); 

most people don't bother 2 phase commits using mongo. if need this, perhaps using wrong tool.

if node save fails, user won't saved. if can't save node without user being saved, reverse order order of operations. if both must updated either be, i'd rethink data model.

if need 2 phase commit, need reinvent particular wheel. there's recipe doing in documentation. or can try 1 of mongoose plugins purport it.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -