
MongoDB utils for Node.js

Installation
npm install --save mongodb-utils
Usage
MongoDB utils overide the collection
class by adding an utils
object that will expose all the MongoDB utils methods:
const mongoUtils = require('mongodb-utils')
const collection = mongoUtils(db.collection('users'))
const user = await collection.utils.get({ usermane: 'terrajs' })
Methods
get
get(query = { key: value } || string || ObjectID, [fields]): Promise<doc>
Return a document that match the specific identifier (_id
by default) or the query:
collection.utils.get('59c0de2dfe8fa448605b1d89')
collection.utils.get({ username: 'terrajs' })
collection.utils.get({ username: 'terrajs' }, { _id: 1 })
collection.utils.get({ username: 'terrajs' }, ['_id'])
create
create(doc: object): Promise<doc>
Insert a document into the collection and add createdAt
and updatedAt
properties:
const user = await collection.utils.create({ username: 'terrajs' })
update
update(query = { key: value } || string || ObjectID, doc: object): Promise<doc>
Update a specific document and update the updatedAt
value
await collection.utils.update('59c0de2dfe8fa448605b1d89', { username: 'terrajs2' })
await collection.utils.update({ username: 'terrajs2' }, { username: 'terrajs' })
upsert
upsert(query = { key: value } || string || ObjectID, doc: object): Promise<doc>
Update or create a document if not exist
Add the createdAt
if document not exist
await collection.utils.upsert('59c0de2dfe8fa448605b1d89', { username: 'terrajs2' })
await collection.utils.upsert({ username: 'terrajs2' }, { username: 'terrajs' })
remove
remove(query = { key: value } || string || ObjectID): Promise<boolean>
Remove a document that match the specific identifier (_id
by default) or the query:
const result = collection.utils.remove('59c0de2dfe8fa448605b1d89')
collection.utils.remove({ username: 'test' })
find
find(query = { key: value } || string || ObjectID, [options = { fields: ..., limit: ..., offset: ..., sort: ... }]): cursor
The find method return a mongo cursor from a specific query and options.
Options:
fields
: Array of keys (['username', ...]
) to return OR a MongoDB projection ({ field1: 1, ... }
), default: {}
limit
: Nb of docs to return, no limit by defaultoffset
: Nb of docs to skpi, default: 0
sort
: Sort criteria (same as sort
method from mongo cursor), default: {}
const users = await userCollection.mono.find({
username: new RegExp(/^test/g)
}, {
fields: ['username', 'createdAt'],
limit: 10
}).toArray()