chatra:mongo-null-unset
Automatically converts null
values in $set
operations to $unset
operations in Meteor's MongoDB collections.
Table of Contents
Introduction
In Meteor applications, unsetting a field from a MongoDB document requires using the $unset
operator explicitly. The chatra:mongo-null-unset
package simplifies this process by allowing developers to unset fields by setting them to null
in $set
operations. This package automatically transforms null
values in $set
operations into $unset
operations.
Installation
Install the package using Meteor's package manager:
meteor add chatra:mongo-null-unset
Usage
Once installed, the package automatically modifies the behavior of insert
, update
, and upsert
methods on all MongoDB collections in your Meteor application.
Updating Documents
-
Unsetting Fields: To unset a field, set its value to
null
in your$set
operation. -
Example:
1MyCollection.update( 2 { _id: 'documentId' }, 3 { 4 $set: { 5 fieldToKeep: 'value', 6 fieldToUnset: null, // This will unset the field 7 }, 8 } 9);
Inserting Documents
-
Denullification on Insert: When inserting documents, any
null
values are removed from the document before insertion. -
Example:
1MyCollection.insert({ 2 field1: 'value1', 3 field2: null, // This field will be removed before insertion 4 nestedField: { 5 subField1: 'subValue1', 6 subField2: null, // This field will also be removed 7 }, 8});
Examples
Unsetting Fields with null
1// Define your collection 2const Tasks = new Mongo.Collection('tasks'); 3 4// Update a task, unsetting the 'completedAt' field 5Tasks.update( 6 { _id: 'taskId' }, 7 { 8 $set: { 9 title: 'Updated Task Title', 10 completedAt: null, // This will unset 'completedAt' 11 }, 12 } 13); 14 15// The 'completedAt' field is now removed from the document
Inserting Documents without null
Values
1// Insert a new user, 'middleName' will be omitted 2Users.insert({ 3 firstName: 'John', 4 lastName: 'Doe', 5 middleName: null, // Will be removed 6 profile: { 7 age: 30, 8 nickname: null, // Will be removed 9 }, 10});
Tests
To run the tests:
meteor test-packages ./
License
This package is licensed under the MIT License.