mongo-dot-notation
Convert simple objects to mongo update operators.

This lightweight library can be used to create a more readable code when working with mongo updates.
You focus on updated properties of the document, rather than on mongo update instructions.
Example:
var $ = require('mongo-dot-notation');
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/mydatabase';
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var update = {
$set: {
'comment': 'Logged in.',
'system': 'demo',
'account.attempts': 0
},
$currentDate: {
'login.date': true
},
$inc: {
'analytics.visits': 1,
'account.logins': 1,
},
$unset: {
'account.blocked'
}
}
updateUser(db, update, function(err, res){
db.close();
})
var update = {
comment: 'Logged in.',
system: 'demo',
login: {
date: $.$currentDate()
},
analytics: {
visits: $.$inc()
},
account: {
blocked: $.$unset(),
attempts: 0,
logins: $.$inc()
}
}
updateUser(db, $.flatten(update), function(err, res){
db.close();
})
});
function updateUser(db, user, handler){
var collection = db.collection('users');
collection.update({username: 'johndoe@test.com'}, user, handler);
}
The current implementation supports all mongo update operators:
- $inc
- $mul
- $rename
- $setOnInsert
- $set
- $unset
- $min
- $max
- $currentDate
- use $currentDate for conversion to $type = 'date'
- use $timestamp for conversion to $type = 'timestamp'
Installation
Install from npm:
npm install mongo-dot-notation --save
Usage
Convert a simple object
var $ = require('mongo-dot-notation');
var person = {
firstName: 'John',
lastName: 'Doe'
};
var instructions = $.flatten(person)
console.log(instructions);
Convert an object with deep properties
var $ = require('mongo-dot-notation');
var person = {
firstName: 'John',
lastName: 'Doe',
address: {
city: 'NY',
street: 'Eighth Avenu',
number: 123
}
};
var instructions = $.flatten(person)
console.log(instructions);
Using operators
var $ = require('mongo-dot-notation');
var person = {
password: '1234',
updated: $.$currentDate(),
resetCounter: $.$inc()
};
var instructions = $.flatten(person)
console.log(instructions);
Operators can also be used in inner objects:
var $ = require('mongo-dot-notation');
var pos = {
coords: {
x: $.$mul(2),
y: $.$inc(10),
z: $.$unset(),
mark: [1, 2, 3]
},
label: $.$rename('title')
};
var instructions = $.flatten(pos)
console.log(instructions);
Operators cannot be used inside arrays.
Update operators signatures
See MongoDB - Fields update operators.
var $ = require('mongo-dot-notation');
Copyright © 2015-2017 Dumitru Deveatii, released under the MIT license