LearnBoost/mongoose — pull request #2508 by jondavidjohn (2014-12-04 03:26:43+00:00)
Title: Reset document only upon save success

Pulled this out of the google group:

https://groups.google.com/forum/#!topic/mongoose-orm/1BGNX_GG8kk

> When I change a path in a document and save it, if the save operation fails (due to a duplicate key, for example), the path I've modified is now not marked as modified anymore.
This implies that if I try to save again, that path won't be updated and now I have a inconsistent document in memory.

```javascript
// Now we're going to finalize order2
// We choose a random code for it
order2.isFinalized = true
order2.code = code
order2.save(function (err) {
// Unfortunately the code is taken (duplicate key error)
assert(err)
assert(err.code === 11001 || err.code === 11000)

// No problem, pick another code and try again
order2.code = code2
order2.save(function (err) {
// This time it's fine
assert.ifError(err)

// Now if we check the DB...
Order.findById(order2, function (err, order2InDB) {
assert.ifError(err)

// save() hasn't saved the isFinalized path
assert(order2.isFinalized)
assert(order2InDB.isFinalized) // this will throw
})
})
})
```