- Node Mongo
- Mongo Query Service
- Mongo Service
once(eventName, handler)
on(eventName, handler)
create(objects)
update(query, updateFn)
atomic.update(query, updateObject, [updateOptions])
remove(query)
ensureIndex(index, options)
createOrUpdate(query, updateFn)
findOneAndUpdate(query, update, [options])
atomic.findOneAndUpdate(query, update, [updateOptions])
onPropertiesUpdated(properties, callback)
Connect to the database MongoDB.
connectionString
- (String) string to connect to database, contains host, port and user credentials if it's needed and other parameters (MongoDB documentation).
New database object.
const connectionString = `mongodb://localhost:27017/home-db`;
const db = require('node-mongo').connect(connectionString);
Create and return new MongoDB service
-
collectionName
- (String) the name of the collection with which the service will work. -
validateSchema
- (function) optional function that accepts a collection document as a parameter and returns the result of the validation of this document. We recommend to to use joi for validation. Or you can use jsonshema for validation.On every update service will validate schema before save data to the database. While schema is optional, we highly recommend use it for every service. We believe that
joi
is one of the best libraries for validation of the schema, because it allows us to do the following things:- Validate the schemas with a variety of variations in data types
- It is easy to redefine the text for validation errors
- Write conditional validations for fields when some conditions are met for other fields
- Do some transformations of the values (for example for string fields you can do
trim
)
-
options
- (Object) optional object with options of the service.
New MongoDB service object.
const Joi = require('Joi');
const subscriptionSchema = {
appId: Joi.string(),
plan: Joi.string().valid('free', 'standard'),
subscribedOn: Joi.date().allow(null),
cancelledOn: Joi.date().allow(null),
};
const companySchema = {
_id: Joi.string(),
createdOn: Joi.date(),
updatedOn: Joi.date(),
name: Joi.string(),
isOnDemand: Joi.boolean().default(false),,
status: Joi.string().valid('active', 'inactive'),
subscriptions: Joi.array().items(
Joi.object().keys(subscriptionSchema)
),
};
const joiOptions = {};
module.exports = (obj) => Joi.validate(obj, companySchema, joiOptions);
// Use schema when creating service. user.service.js file:
const schema = require('./user.schema')
const usersService = db.createService('users', schema);
Add custom method for Mongo service.
name
- (String) name of the method, that will be used to call method.method
- (function) custom function in which we can manipulate the collection. The custom function takes the service itself as the first parameter, and the remaining parameters are the parameters that are passed when this custom function is called.
const connectionString = `mongodb://localhost:27017/home-db`;
const db = require('node-mongo').connect(connectionString);
db.setServiceMethod('createByName', async (service, name) => {
const res = await service.create({ name });
return res;
});
// Create entity service
const usersQueryService = db.createQueryService('users');
// find user by id
const user = await usersQueryService.findById('123')
Create and return new MongoDB Query Service
collectionName
- (String) name of the MongoDB collection.options
- (Object) optional object with options of the service (currently, specified options are not used in the service)
const usersService = db.createQueryService('users');
Add custom method for Mongo Query Service.
name
- (String) name of the method, that will be used to call method.method
- (function) custom function in which we can manipulate the collection. The custom function takes the service itself as the first parameter, and the remaining parameters are the parameters that are passed when this custom function is called.
const connectionString = `mongodb://localhost:27017/home-db`;
const db = require('node-mongo').connect(connectionString);
db.setQueryServiceMethod('findById', (service, id) => {
return service.findOne({ _id: id });
});
Mongo Query Service allows you to make requests to the database to get needed data, but this service not allow to modify data in the database.
Get name of the collection for which service was created.
Get documents from the collection that satisfy the condition.
query
- (Object) optional object, according to which we receive documents.options
- (Object) optional object with options for query.perPage
- (Number) optional number of returned documents, default value is100
.page
- (Number) optional page number with results, default value is0
.fields
- (Object) optional projection object (fields that must be included or excluded from the result), by default we will return unmodified documents.rawCursor
- (Boolean) optional parameter to get the raw mongo cursor when the promise resolve.
This async method returns an object with following fields:
pagesCount
- (Number) total number of pages.results
- (Object[]) array of documents.count
- (Number) total number of documents that satisfy the condition.
const connectionString = `mongodb://localhost:27017/home-db`;
const db = require('node-mongo').connect(connectionString);
const usersService = db.createService('users');
const result = await usersService.find({ name: 'Bob' }, { page: 1, perPage: 30 });
// returns object like this:
// {
// results: [], // array of user entities
// pagesCount, // total number of pages
// count, // total count of documents found by query
// }
Get one document that satisfies the specified condition.
query
- (Object) optional object, according to which we receive document.options
- (Object) optional object with options for query.fields
- (Object) optional projection object (fields that must be included or excluded from the result), by default we will return unmodified documents.rawCursor
- (Boolean) optional parameter to get the raw mongo cursor when the promise resolve.
Async function returns document or null
. If several documents satisfy the condition, then we throw an error.
const usersService = db.createService('users');
try {
const user = await usersService.findOne({ name: 'Bob' });
} catch (error) {
console.error('Several users were found.');
}
Get the number of documents that meet the specified condition.
query
- (Object) object with conditions for selection.
Promise that resolve number of documents.
const usersService = db.createService('users');
const usersNumber = await usersService.count({ name: 'Bob' });
This method is a simple wrapper of the distinct
method of the monk
. You can find documention here.
Async method to get existence of the documents that meet the specified condition.
query
- (Object) object with conditions for selection.
Boolean value.
const usersService = db.createService('users');
const usersExist = await usersService.exists({ name: 'Bob' });
This method is a simple wrapper of the aggregate
method of the monk
. You can find documention here.
Get id for mongoDB documents.
Id string.
const usersService = db.createService('users');
const id = usersService.generateId();
Wait, until certain document added or removed from database, typically used in the integrational tests.
query
- (Object) object with conditions for selection.options
- (Object) optional object with the following options:timeout
- (Number) maximum waiting time (ms), default value is10000
.tick
- (Number) gap between requests to the database, default value is50
.expectNoDocs
- (Boolean) specifies the expected state of the document (added or deleted), default value isfalse
.
Promise which call resolve
when the expected state is reached. If the expected state is not reached within a given time, then an error is thrown.
const usersService = db.createService('users');
try {
await usersService.expectDocument({ name: 'Bob'}, {
timeout: 10000,
tick: 50,
expectNoDocs: false,
});
} catch (error) {
console.error('Document was not added');
}
Mongo Service extends Mongo Query Service, therefore instance of this service has all methods of the Mongo Query Service.
Subscribe to database change events only once. The first time evenName is triggered listener handler is removed and then invoked.
eventName
- (String) name of the database eventhandler
- (function) function event handler
Returns a reference to the EventEmitter
.
const usersService = db.createService('users');
userService.once('updated', ({ doc, prevDoc }) => {
});
Subscribe to database change events.
eventName
- (String) name of the database eventhandler
- (function) function event handler
Returns a reference to the EventEmitter
.
const usersService = db.createService('users');
userService.on('updated', ({ doc, prevDoc }) => {
});
Async function that insert one object or array of the objects to the database. Publishes created
event {doc}. Sets createdOn to the current date. If the schema for validation specified in the moment of creating service, then it is used within this method.
objects
- (Object[]|Object) Object or array of objects to create
Object or array of created objects
const usersService = db.createService('users');
await userService.create([{ name: 'Bob' }, { name: 'Alice' }]);
Async function that modifies entity found by query in the database. Publishes updated
event {doc, prevDoc}. Sets updatedOn to the current date. If the schema for validation specified in the moment of creating service, then it is used within this method.
query
- (Object) mongo search queryupdateFn
- (function) function, that recieves document to be updated
Updated document.
const usersService = db.createService('users');
const updatedUser = await usersService.update({ _id: '1'}, (doc) => {
doc.name = 'Alex';
});
This method is a simple wrapper of the update
method of the monk
. You can find documention here. This method doesn't publish updated
event.
Async function to remove one or many documents found by query.
query
- (Object) mongo search query
Removed documents.
const usersService = db.createService('users');
const removeUsers = await usersService.remove({ name: 'Alex' });
Create or check index existence. This method is a wrapper of the createIndex
method of the monk
. You can find documention here. This method omits error.
Async method, that updates documents or create new document if there are no documents that satisfy the condition.
query
- (Object) mongo search queryupdateFn
- (function) function, that recieves document to be updated
Updated or created document.
const usersService = db.createService('users');
const userHelen = await usersService.createOrUpdate({ _id: 1 }, (doc) => {
doc.name = 'Helen';
});
Update or create new document using update
object. This method emits updated
or created
event.
query
- (Object) mongo search queryupdate
- (Object) update operations to be performed on the documentoptions
- (Object) optional object with optionsreturnOriginal
- (Boolean) return original or updated document
Promise that resolves document.
const usersService = db.createService('users');
const newUser = await usersService.findOneAndUpdate({ name: 'Bob'}, {
$set: {
name: 'Alice',
},
});
This method is a simple wrapper of the findOneAndUpdate
method of the monk
. You can find documention here. This method doesn't publish any event.
Deep compare doc & prevDoc from updated
event. When something changed - executes callback.
properties
- (Object[]|Object) properties to comparecallback
- (function) executes callback if something changed
Returns a reference to the EventEmitter
.
// Listen to the value changes between original and updated document
// Callback executed only if user lastName or firstName are different in current or updated document
userService.onPropertiesUpdated(['user.firstName', 'user.lastName'], ({ doc, prevDoc }) => {
});
// Listen to the value changes between original and updated document
// Callback executed only if user first name changes to `Bob`
const propertiesObject = { 'user.firstName': 'Bob' };
userService.onPropertiesUpdated(propertiesObject, ({ doc, prevDoc }) => {
});