Safer collection.update


Recently erased 45 docs in the database because of the stupid behavior collection.update Meteor.

This is the story of of how the idea of safe-update came.

Look out!

The behavior of collection.update in Meteor a bit dangerous.

If you forget to add a $set operator to a mongo modifier or and other $-operators (like $set, $unset, $inc, etc.), then it is instead interpreted as a literal document, and completely replaces whatever was previously in the database.
You may accidentally lose a document if you write this:

Docs.update('f7uJjPPQJP7Ytf3pE', {important: 1});

…instead of this:

Docs.update('f7uJjPPQJP7Ytf3pE', {$set: {important: 1}});


This package protects you from this and throws if there is no $-operators in the modifier:

Docs.update('f7uJjPPQJP7Ytf3pE', {important: 1});
// /!\ Error: modifier doesn’t contain any $-operators...

But if you still want to rewrite the entire document, just pass the replace:true to the options object:

Docs.update('f7uJjPPQJP7Ytf3pE', {deleted: 1}, {replace: true});
// → One doc updated successfully


meteor add artpolikarpov:safe-update


Just use collection.update as usual. You will be warned in case of danger of replacing the docs.
But if replacement of the whole document is what you need, force it using replace:true.






Looks awesome! I’ve also run into this unfortunate situation with update in MongoDB. (You’d think $set would be the default!)


While I’ve never ran into it, it seems like more than a useful thing. Added to my app :smile: Thanks a bunch!


Never had this problem, and now I never will! Thanks!