Make Meteor’s collection.update/collection.updateAsync safer by preventing unintended updates and enforcing best practices.
The chatra:safe-update package enhances the safety of MongoDB update operations in Meteor applications by:
- Preventing updates with empty selectors unless explicitly allowed.
- Ensuring that updates use modifier operators (e.g.,
$set,$inc) unless thereplaceoption is specified. - Providing configuration options to include or exclude specific collections.
meteor add chatra:safe-update- Meteor Version 3 and Above: Fully compatible, using the new asynchronous Meteor collections’ methods.
- Meteor Version 2: Maintains compatibility with synchronous methods.
By default, the package throws an error if you attempt to perform an update with an empty selector:
// Throws an error
MyCollection.update({}, { $set: { field: 'value' } });To allow updates with an empty selector, pass allowEmptySelector: true in the options:
// Allowed
MyCollection.update({}, { $set: { field: 'value' } }, { allowEmptySelector: true });The package ensures that you use modifier operators (e.g., $set, $inc) in your updates:
// Throws an error
MyCollection.update({ _id: 'docId' }, { field: 'value' });To replace a document entirely, pass replace: true in the options:
// Allowed
MyCollection.update({ _id: 'docId' }, { field: 'value' }, { replace: true });To configure the package behavior, use the setSafeUpdateConfig function provided by the package:
import { setSafeUpdateConfig } from 'meteor/chatra:safe-update';
setSafeUpdateConfig({
except: ['logs'], // Collections to exclude from safety checks
only: ['users', 'posts'], // Only apply safety checks to these collections
});except: An array of collection names to exclude from the safety checks.only: An array of collection names to include in the safety checks (all others are excluded).
import { Mongo } from 'meteor/mongo';
const Messages = new Mongo.Collection('messages');
// Safe update with modifier
Messages.update({ _id: 'msgId' }, { $set: { text: 'Updated message' } });
await Messages.updateAsync({ _id: 'msgId' }, { $set: { text: 'Updated message' } });
// Unsafe update without modifier (throws error)
Messages.update({ _id: 'msgId' }, { text: 'Updated message' }); // Throws error
await Messages.updateAsync({ _id: 'msgId' }, { text: 'Updated message' }); // Throws error
// Replacing document with replace option
Messages.update({ _id: 'msgId' }, { text: 'Updated message' }, { replace: true });
await Messages.updateAsync({ _id: 'msgId' }, { text: 'Updated message' }, { replace: true });The package includes a comprehensive test suite. To run the tests:
meteor test-packages ./This package is licensed under the MIT License.