Connect to MongoDB.
connectionString: String
- connection string.connectionSettings: Object
- optional connection settings.
A Manager instance.
const db = require('node-mongo').connect(
'mongodb://localhost:27017/home',
{ poolSize: 10 },
);
Create and return Query Service instance.
collectionName: String
- name of the MongoDB collection.
A Query Service instance.
const usersQueryService = db.createQueryService('users');
Add custom method for Query Service.
name: String
- name of the method, that will be used to call method.method: (QueryService, ...args) => any
- 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 db = require('node-mongo').connect(connectionString);
db.setQueryServiceMethod('findByName', (service, name, options) => {
return service.findOne({ name }, { collation: 'en', ...options });
});
const userService = db.createQueryService('users');
const user = userService.findByName('Bob', { projection: { name: 1, age: 1 } });
Create and return Service instance.
collectionName: String
- the name of the collection with which the service will work.options: Object
- optional object with options of the service.addCreatedOnField: Boolean = true
- iftrue
, we add thecreatedOn
field for each document to be created using the create method.addUpdatedOnField: Boolean = true
- iftrue
, we add and update theupdatedOn
field for each document to be updated using updateOne or updateMany methods.useStringId: Boolean = true
- iftrue
, we replace_id
(ObjectId by default) with a string that is generated using the generateId method.validate: (doc) => Promise<{ error, value }>
- optional function that accepts a collection document and returns the result of the validation of this document. Result should be an object withvalue
anderror
fields. The error will be thrown iferror
is a truthy value.emitter: Emitter = new EventEmitter()
- optional instance of Emitter, which partially implements the EventEmitter interface (emit, on, once methods are enough).
A Service instance.
user.schema.js
const Joi = require('Joi');
const userSchema = Joi.object({
_id: Joi.string(),
createdOn: Joi.date(),
updatedOn: Joi.date(),
name: Joi.string(),
status: Joi.string().valid('active', 'inactive'),
});
// you can use validate method from Joi
module.validate = (obj) => userSchema.validate(obj);
// or it could be your custom function
module.validate = (obj) => {
if (!obj.name) {
return {
value: obj,
error: {
details: [{ message: 'Name is required' }],
},
};
}
return { value: obj };
};
user.service.js
const { validate } = require('./user.schema');
const userService = db.createService('users', {
useStringId: false,
validate,
});
Add custom method for Service.
name: String
- name of the method, that will be used to call method.method: (Service, ...args) => any
- 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 db = require('node-mongo').connect(connectionString);
db.setServiceMethod('createByName', (service, name) => {
return service.create({ name });
});
const userService = db.createService('users');
const user = userService.createByName('Bob');
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.
Name of the collection for which service was created.
const db = require('node-mongo').connect(connectionString);
const userQueryService = db.createQueryService('users');
console.log(userQueryService.name); // users
Gets existence of the documents matching the filter. Under the hood, count method is used.
Boolean value.
const userService = db.createService('users');
const userExists = await userService.exists({ name: 'Bob' });
Gets documents matching the filter. Under the hood, monk's find method is used.
query: Object
- object, according to which we receive documents.options: Object
- optional object with options for query.perPage: Number = 100
- optional number of returned documents.page: Number = 0
- optional page number with results.rawCursor: Boolean
- optional parameter to get the raw mongo cursor. You can find more usage examples in monk docs.- ...default mongo options
An object with following fields:
results: Object[]
- array of documents.
Additional fields will be added, if the page
option exists and is greater than zero:
pagesCount: Number
- total number of pages.count: Number
- total number of documents that satisfy the condition.
const db = require('node-mongo').connect(connectionString);
const userQueryService = db.createQueryService('users');
const { results, pagesCount, count } = await userQueryService.find(
{ name: 'Bob' },
{ page: 1, perPage: 30 },
);
Get one document that satisfies the specified condition. Under the hood, find method is used.
A document or null
. If several documents satisfy the condition, then we throw an error.
const userService = db.createService('users');
try {
const user = await userService.findOne({ name: 'Bob' });
} catch (error) {
console.error('Several users were found');
}
Calculates aggregate values for the data in a collection.
Monk's method. Under the hood, native aggregate method is used.
Gets the number of documents matching the filter.
Monk's method. Under the hood, native countDocuments method is used.
The distinct command returns a list of distinct values for the given key across a collection.
Monk's method. Under the hood, native distinct method is used.
Execute a geo search using a geo haystack index on a collection.
Monk's method. Under the hood, native geoHaystackSearch method is used.
Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
Monk's method. Under the hood, native indexes method is used.
Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.
Monk's method. Under the hood, native mapReduce method is used.
Get all the collection statistics.
Monk's method. Under the hood, native stats method is used.
Service extends Query Service, therefore instance of this service has all methods of the Query Service.
Service emits events that you can subscribe to. Please note that only the methods mentioned below can emit events.
created
β emits when you create a document with create method.updated
β emits when you create a document with updateOne or updateMany methods.removed
β emits when you remove a document with remove method.
Methods in the atomic
namespace are ordinary monk's methods. They don't emit any events and don't validate data.
- on
- once
- onPropertiesUpdated
- generateId
- create
- updateOne
- updateMany
- remove
- performTransaction
- atomic.bulkWrite
- atomic.createIndex
- atomic.drop
- atomic.dropIndex
- atomic.dropIndexes
- atomic.findOneAndDelete
- atomic.findOneAndUpdate
- atomic.insert
- atomic.remove
- atomic.update
Subscribes to database change events.
eventName: String
- name of the database event.handler: ({ doc, prevDoc }) => any
- event handler.
A reference to the EventEmitter
.
const userService = db.createService('users');
userService.on('updated', ({ doc, prevDoc }) => {
});
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 event.handler: ({ doc, prevDoc }) => any
- event handler.
Returns a reference to the EventEmitter
.
const userService = db.createService('users');
userService.once('updated', ({ doc, prevDoc }) => {
});
Deep compare doc and prevDoc from updated
event. When something changed - executes callback.
properties: String[] | Object
- properties to comparehandler: ({ doc, prevDoc }) => any
- event handler.
A reference to the EventEmitter
.
const userService = db.createService('users');
// Callback executed only if user lastName or firstName are different in current or updated document
userService.onPropertiesUpdated(
['user.firstName', 'user.lastName'],
({ doc, prevDoc }) => {},
);
// Callback executed only if user first name changes to `Bob`
userService.onPropertiesUpdated(
{ 'user.firstName': 'Bob' },
({ doc, prevDoc }) => {},
);
Get ID for mongoDB documents.
ID string.
const userService = db.createService('users');
const id = userService.generateId();
Inserts one object or array of the objects to the database. Validates the documents before creation if service was created with validate
option. Adds createdOn
field to the document. Publishes the created
event.
documents: Object | Object[]
- object or array of objects to create.
Object or array of created objects.
const userService = db.createService('users');
const users = await userService.create([
{ name: 'Bob' },
{ name: 'Alice' },
]);
Updates entity found by query in the database. Validates the document before save if service was created with validate
option. Updates updatedOn
field in the document. Publishes the updated
event. Throws out an error if more than one document is found or if no document is found.
query: Object
- query for findOne operation.updateFn: (doc) => doc
- update function that recieves old document and should return updated one.options: Object
- optional options for findOne operation.
Updated document.
const userService = db.createService('users');
try {
const updatedUser = await userService.updateOne(
{ _id: '1'},
(doc) => ({ ...name, name: 'Alex' }),
);
} catch (error) {
console.error(error.message);
}
Updates entity found by query in the database. Validates the documents before save if service was created with validate
option. Updates updatedOn
field in the every the document. Publishes the updated
event for every document.
query: Object
- query for find operation.updateFn: (doc) => doc
- update function that recieves old document and should return updated one.options: Object
- optional options for find operation.
Array of updated documents.
const userService = db.createService('users');
const updatedUsers = await userService.updateMany(
{ age: '27' },
(doc) => ({ ...name, alive: false }),
);
Removes documents found by query. Publishes the removed
event for every document.
Array of removed documents.
const userService = db.createService('users');
const removedUsers = await userService.remove({ name: 'Alex' });
Starts a new session, performs transaction and ends this session.
transactionFn: (Session) => Promise<any>
- function to be performed within a transaction. It must return Promise.options: Object
- optional settings for startSession operation.
Resulting Promise of operations run within transaction.
const userService = db.createService('users');
const teamService = db.createService('teams');
await userService.performTransaction(async (session) => {
await userService.create({}, { session });
await teamService.create({}, { session });
});
Perform a bulkWrite operation without a fluent API.
Monk's method. Under the hood, native bulkWrite method is used.
Creates an index on the db and collection (will not create if already exists).
Monk's method. Under the hood, native createIndex method is used.
Drop the collection from the database, removing it permanently. New accesses will create a new collection.
Monk's method. Under the hood, native drop method is used.
Drops indexes from this collection.
Monk's method. Under the hood, native dropIndex method is used.
Drops all indexes from this collection.
Monk's method. Under the hood, native dropIndexes method is used.
Find a document and delete it in one atomic operation.
Monk's method. Under the hood, native findOneAndDelete method is used.
Find a document and update it in one atomic operation.
Monk's method. Under the hood, native findOneAndUpdate method is used.
Inserts a single document or a an array of documents into MongoDB.
Monk's method. Under the hood, native insertOne and insertMany methods are used.
Remove documents.
Monk's method. Under the hood, native deleteOne and deleteMany methods are used.
Modifies an existing document or documents in a collection.
Monk's method. Under the hood, native updateOne and updateMany methods are used.