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 = const collection = // We can now access to mongodb-utils method from .utilsconst user = await collectionutils
Methods
get
: Promise<doc>
Return a document that match the specific identifier (_id
by default) or the query:
// Get the document that match the query { _id: ObjectID('59c0de2dfe8fa448605b1d89') }collectionutils // Get the document that match the query { username: 'terrajs' }collectionutils // Get the document that match the query & return only its _idcollectionutils// Get the document that match the query & return only its _id (works with array too)collectionutils
create
: Promise<doc>
Insert a document into the collection and add createdAt
and updatedAt
properties:
// Add a document into the collection and return the created documentconst user = await collectionutils
update
: Promise<doc>
Update a specific document and update the updatedAt
value
// Update the document that match the query { _id: ObjectID('59c0de2dfe8fa448605b1d89') } and update its usernameawait collectionutils // Update the document that match the query { username: 'terrajs2' } and update its usernameawait collectionutils
upsert
: Promise<doc>
Update or create a document if not exist
Add the createdAt
if document not exist
// Update the document that match the query { _id: ObjectID('59c0de2dfe8fa448605b1d89') } and update its username or create it if not existawait collectionutils // Update the document that match the query { username: 'terrajs2' } and update its username OR create it if not foundawait collectionutils
remove
: Promise<boolean>
Remove a document that match the specific identifier (_id
by default) or the query:
// Remove the document that match the query { _id: ObjectID('59c0de2dfe8fa448605b1d89') }const result = collectionutils // Remove the document that match the query { username: 'test' }collectionutils
find
: 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 assort
method from mongo cursor), default:{}
// Find documents that matches the query { username: new RegExp(/^test/g) }, options with { username: 1, createdAt: 1 } projection and limit at 10 elementsconst users = await userCollectionmono