e-oj / Fawn

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

Not rolling back #74

Open harshadp37 opened 5 years ago

harshadp37 commented 5 years ago

Comment.findOne({ _id: req.params.commentID }, (err, doc) => { if (err) { res.json({ success: false, message: 'Reply not Saved...Something went Wrong.' }) } else if (!doc) { res.json({ success: false, message: 'Reply not Saved...Something went Wrong.' }) } else { User.findOne({ username: doc.createdBy }, { notificationList: 1 }, (err, user) => { if (err) { res.json({ success: false, message: err }); } else if (!user) { res.json({ success: false, message: "Reply not Saved...Something went Wrong." }); } else { var newReply = new Reply({ repliedBy: req.body.username, body: req.body.replyBody, createdAt: Date.now() })

                    task.save(newReply)  //1st
                        .update(doc, { $push: { replys: newReply } })  //2nd
                        .save(Notification({
                        user: doc.createdBy,
                        body: req.body.username + " replied on your comment",
                        target: {
                            post : doc.post,
                            commentI : doc,  //Field is commentID..it gives me MongoError but not rolling back 1st & 2nd
                            replyID: newReply
                        }
                    }))
                     .run({ useMongoose: true })
                        .then((results) => {
                            res.json({ success: true, result: results })
                        })
                        .catch((err) => {
                            res.json({ success: false, Error: err })
                        })
                }
            })
harshadp37 commented 5 years ago

there are 3 queries that needs to be run...1st saving reply in Reply collection..2nd updating comment collection with newReply's id...3rd save new Notification in Notification collection

i have intentionally made mistake while saving 3rd query so that error should occur... it is giving me MongoError but also it stores result of 1st & 2nd query in database permenently

e-oj commented 5 years ago

I've not been able to reproduce this error. The following script rolls back the changes as expected:

let mongoose = require("mongoose");
let Fawn = require("./lib/fawn");

mongoose.connect("mongodb://127.0.0.1:27017/testDB");
Fawn.init(mongoose);

let task = Fawn.Task();
let Reply = mongoose.model("replies", new mongoose.Schema({
  text: {type: String, required: true},
  list: {type: [String], required: true}
}));

task = task.save(Reply, {text: "I replied!", list: ["some val"]})
  .save(Reply, {text: "I replied again!", list: ["Another One!"]})
  .update(Reply, {_id: {$ojFuture: "0._id"}}, {$push: {list: 3}})
  .save(Reply({
    tex: "bad reply",
    list: ["good list"]
  }));

(async () => {
  try{
    await task.run({useMongoose: true});
  }
  catch(err){
    console.log(err);
  }

  try{
    let replies = await Reply.find();
    console.log("replies: ", replies);
  }
  catch(err){
    console.log(err);
  }
})();

Let me know if I'm missing something.

e-oj commented 5 years ago

This is the output I got btw:

{ ValidationError: replies validation failed: text: Path `text` is required.
    at ValidationError.inspect (/Users/emmanuelolaojo/Desktop/Fawn/node_modules/mongoose/lib/error/validation.js:57:23)
    at ValidationError.deprecated (internal/util.js:70:15)
    at formatValue (util.js:467:31)
    at inspect (util.js:328:10)
    at Object.formatWithOptions (util.js:182:12)
    at Console.(anonymous function) (console.js:188:15)
    at Console.log (console.js:199:31)
    at /Users/emmanuelolaojo/Desktop/Fawn/test.js:31:13
  errors:
   { text:
      { ValidatorError: Path `text` is required.
          at new ValidatorError (/Users/emmanuelolaojo/Desktop/Fawn/node_modules/mongoose/lib/error/validator.js:25:11)
          at validate (/Users/emmanuelolaojo/Desktop/Fawn/node_modules/mongoose/lib/schematype.js:758:13)
          at /Users/emmanuelolaojo/Desktop/Fawn/node_modules/mongoose/lib/schematype.js:805:11
          at Array.forEach (<anonymous>)
          at SchemaString.SchemaType.doValidate (/Users/emmanuelolaojo/Desktop/Fawn/node_modules/mongoose/lib/schematype.js:765:19)
          at /Users/emmanuelolaojo/Desktop/Fawn/node_modules/mongoose/lib/document.js:1506:9
          at process._tickCallback (internal/process/next_tick.js:61:11)
        message: 'Path `text` is required.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'required',
        path: 'text',
        value: undefined,
        reason: undefined,
        '$isValidatorError': true } },
  _message: 'replies validation failed',
  name: 'ValidationError' }
replies:  []
harshadp37 commented 5 years ago

i got this Error : { MongoError: the update operation document must contain atomic operators. at Function.create (C:\Users\Harshad\Desktop\Project\node_modules\mongodb-core\lib\error.js:43:12) at toError (C:\Users\Harshad\Desktop\Project\node_modules\mongodb\lib\utils.js:149:22) at checkForAtomicOperators (C:\Users\Harshad\Desktop\Project\node_modules\mongodb\lib\operations\collection_ops.js:161:12) at Collection.updateOne (C:\Users\Harshad\Desktop\Project\node_modules\mongodb\lib\collection.js:722:15) at NativeCollection.(anonymous function) [as updateOne] (C:\Users\Harshad\Desktop\Project\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:146:28) at C:\Users\Harshad\Desktop\Project\node_modules\fawn\lib\roller.js:163:29 at at process._tickCallback (internal/process/next_tick.js:189:7) driver: true, name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} } replies: [ { list: [ 'some val', '3' ], _id: 5c56f05b1143af13d4e85dc7, text: 'I replied!', __v: 0 }, { list: [ 'Another One!' ], _id: 5c56f05b1143af13d4e85dc8, text: 'I replied again!', __v: 0 } ]

harshadp37 commented 5 years ago

And First 2 replies saved in database

e-oj commented 5 years ago

What's Your version of mongoose and fawn?

harshadp37 commented 5 years ago

Mongoose : 5.4.9 Fawn : 2.1.5

btw i got same Error as u got. i.e Validation Error when i used let Fawn = require("./lib/fawn");

e-oj commented 5 years ago

It's tied to the mongoose version. Fawn uses v4.12.3 and I was able to reproduce the error by upgrading to 5.4.9. This issue will be addressed in the next update. I'll look for other upgrade related bugs as well. Thanks for pointing this out.

harshadp37 commented 5 years ago

Yeah i also got this just now...working perfectly with mongoose@4.13.18..but not with latest version of mongoose i.e mongoose@5.4.9

harshadp37 commented 5 years ago

Thanks for ur time..waiting for next update