Handy MongoDB layer for Node.JS 8
Currently based on monk.
Install as npm package: npm i @paralect/mongo-node8
There are few reasons, why we think this layer could be helpful to many projects:
- Every update method emits
*.updated
, *.created
, *.removed
events, which allow to listen for the database changes and perform business logic based on this updates. That could help keep your entities weakly coupled with each other. - Implements more high level api, such as paging.
- Implements database schema validation based on jsonschema. See examples below for more details.
Usage example
Examples below cover all API methods currently available.
Full API example Usage
const connectionString = `mongodb://localhost:27017/home-db`;
const db = require('./').connect(connectionString);
const usersService = db.createService('users');
const usersQueryService = db.createQueryService('users');
const result = await usersService.find({ name: 'Bob' }, { page: 1, perPage: 30 });
const result2 = await usersService.find({ name: 'Bob'}, { });
const user = await usersService.findOne({ name: 'Bob' });
const usersCount = await usersService.count({ name: 'Bob'});
const isUserExists = await usersService.exists({ name: 'Bob' });
const distinctNames = await distinct('name');
const aggregate = await aggregate([{ $match: { name: 'Bob'} }]);
const mongoId = usersService.generateId();
await expectDocument({ name: 'Bob'}, {
timeout: 10000,
tick: 50,
expectNoDocs: false,
});
await userService.create([{ name: 'Bob' }, { name: 'Alice' }]);
await usersService.update({ _id: '1'}, (doc) => {
doc.name = 'Alex';
});
await usersService.remove({ _id: 1 });
usersService.ensureIndex({ _id: 1, name: 1});
await usersService.createOrUpdate({ _id: 1 }, (doc) => {
doc.name = 'Helen';
})
await userService.atomic.update({ name: 'Bob' }, {
$set: {
name: 'Alice',
},
}, { multi: true });
await usersService.findOneAndUpdate({ name: 'Bob'}, {
$set: {
name: 'Alice',
},
});
userService.on('updated', ({ doc, prevDoc }) => {
});
userService.on('created', ({ doc, prevDoc }) => {
});
userService.on('removed', ({ doc, prevDoc }) => {
});
const propertiesObject = { 'user.firstName': 'Bob' };
userService.onPropertiesUpdated(['user.firstName', 'user.lastName'], ({ doc, prevDoc }) => {
});
userService.onPropertiesUpdated(propertiesObject, ({ doc, prevDoc }) => {
});
Documents schema validation
Schema validation is based on jsonschema and can be optionally provided to service. 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.
const Validator = require('jsonschema').Validator;
const validator = new Validator();
const subscriptionSchema = {
id: '/Subscription',
type: 'object',
properties: {
appId: { type: 'String' },
plan: { type: 'String', enum: ['free', 'standard'] },
subscribedOn: { type: ['Date', 'null'] },
cancelledOn: { type: ['Date', 'null'] },
},
};
const companySchema = {
id: '/Company',
type: 'object',
properties: {
_id: { type: 'string' },
createdOn: { type: 'Date' },
updatedOn: { type: 'Date' },
name: { type: 'String' },
isOnDemand: { type: 'Boolean' },
status: { type: 'string', enum: ['active', 'inactive'] },
subscriptions: {
type: 'array',
items: { $ref: '/Subscription' },
},
},
required: ['_id', 'createdOn', 'name', 'status'],
};
validator.addSchema(subscriptionSchema, '/Subscription');
module.exports = (obj) => validator.validate(obj, companySchema);
const schema = require('./user.schema')
const usersService = db.createService('users', { validateSchema: schema });