e-oj / Fawn

Transactions for MongoDB (See the README)
https://www.npmjs.com/package/fawn
MIT License
485 stars 54 forks source link

Transaction order #70

Open yamila-fraiman opened 6 years ago

yamila-fraiman commented 6 years ago

I want to update a document from model1 and then remove a document from model2 because I have a hook that when you remove a doc from model2 if it's being used in model1, throws an error. So I have the following code but it seems that it does not take into account the order so it is throwing my custom error "Document is being used"

model1.model2Doc = undefined; transaction .update(model1, model1.toObject()) .options({viaSave: true}) .remove(model2) .run({useMongoose: true})

e-oj commented 6 years ago

Sorry for the late response, I've been really busy lately.

Let me see the code for hook you're using

yamila-fraiman commented 6 years ago

schema.pre('remove', function (next) { let self = this; async.map(options.models, (model, callback) => { let query = {}; if (model.fields || options.fields) { query.$or = []; (model.fields || options.fields).forEach((key) => { let condition = {}; condition[key] = self; query.$or.push(condition); }); } else { let key = model.field || options.field; query[key] = self; } mongoose.model(model.model || model).count(query).exec(callback); }, (err, counts) => { if (err) { return next(err); } if (lodash.sum(counts)) { return next(new Error(queryUtils.ERRORS.FOREIGN_KEY)); } next(); }); });