A node.js module for mongodb built with async/await in mind, that emulates the official mongodb API as much as possible.
Mongoist driver is heavily inspired by mongojs.
The the official MongoDB driver for Node.js (https://github.com/mongodb/node-mongodb-native) leaves connection management to the user, this means to connect to a mongodb database this boilerplate code is needed
const { MongoClient } = require('mongodb');
MongoClient
.connect('mongodb://localhost:27017/myproject')
.then(connection => {
connection.close();
});Due to the asynchronous nature of connect, a connection that is used everywhere in an application is not that easy to export from a module.
const { MongoClient } = require('mongodb');
MongoClient
.connect('mongodb://localhost:27017/myproject')
.then(connection => {
// THIS WILL NOT WORK AS EXPECTED!!!
module.exports = connection;
});Mongoist solves this problem by managing the connection internally in a lazy fashion. With mongoist you can create a db.js module exporting a
not yet opened database connection:
module.exports = mongoist(connectionString);const mongoist = require('mongoist');
const db = mongoist(connectionString, connectionOptions)The connectionString and connectionOptions are passed to the underlying official mongodb driver.
Find out more about connection strings and options.
While mongojs uses callbacks only, mongoist uses promises only. To allow migrating to mongoist without migrating the whole application mongoist supports wrapping the mongojs driver.
const mongojsDb = mongojs(connectionString);
const db = mongoist(mongojsDb);
const docs = await db.a.find({});Mongoist uses the connection pool provided by the official mongodb driver, so there is no need to manage connections on your own.
For most use cases it's best to create a db.js node module that exports a mongoist database connection
module.exports = mongoist(connectionString);Mongoist uses a proxy implementation under the hood to allow accessing a collection named foo as
db.foo.find(...);instead of
db.collection('foo').find(...);// find everything in mycollection returned as array
const documents = await db.mycollection.find();
// find everything in mycollection, but sort by name
const sortedDocuments = await db.mycollection.findAsCursor().sort({name: 1}).toArray();
// find a document using a native ObjectId
const documentById = await db.mycollection.findOne({ _id: mongoist.ObjectId('523209c4561c640000000001') });
// Update all documents named 'mathias' and increment their level
const resultUpdate = await db.mycollection.update({name: 'mathias'}, {$inc: {level: 1}}, {multi: true});
// find one named 'mathias', tag him as a contributor and return the modified doc
const resultFindAndModify = await db.mycollection.findAndModify({
query: { name: 'mathias' },
update: { $set: { tag: 'maintainer' } },
new: true
});
// use the save function to just save a document
const doc = await db.mycollection.save({created: 'just now'});The mongodb operations find and aggregate return a cusors, that is resolved in the mongodb shell to an array. Mongoist
provides the operations findAsCursor and aggregateAsCursor to return a cursor and shorthand functions find and
aggregate that return an array.
var bulk = db.a.initializeOrderedBulkOp()
bulk.find({type: 'water'}).update({$set: {level: 1}})
bulk.find({type: 'water'}).update({$inc: {level: 2}})
bulk.insert({name: 'Spearow', type: 'flying'})
bulk.insert({name: 'Pidgeotto', type: 'flying'})
bulk.insert({name: 'Charmeleon', type: 'fire'})
bulk.find({type: 'flying'}).removeOne()
bulk.find({type: 'fire'}).remove()
bulk.find({type: 'water'}).updateOne({$set: {hp: 100}})
await bulk.execute();
// done...const db = mongoist('mongodb://localhost/mydb')
// Emitted if no db connection could be established
db.on('error', function (err) {
console.log('database error', err)
});
// Emitted if a db connection was established
db.on('connect', function () {
console.log('database connected')
})With mongoist you can run database commands just like with the mongo shell using db.runCommand()
const result = await db.runCommand({ping: 1});
console.log('we\'re up');or db.collection.runCommand()
const result = await db.things.runCommand('count');
console.log(result);Mongoist can connect to a mongo replication set by providing a connection string with multiple hosts
const db = mongoist('rs-1.com,rs-2.com,rs-3.com/mydb?slaveOk=true');For more detailed information about replica sets see the mongo replication docs
This API documentation is a work in progress.
All operations return promises. If a return type is given, this is the type of the resolved promise.
See https://docs.mongodb.org/manual/reference/method/db.collection.aggregate/
Returns a cursor instead of an array as db.collection.aggregate does.
See https://docs.mongodb.org/manual/reference/method/db.collection.aggregate/
See https://docs.mongodb.org/manual/reference/method/db.collection.count/
See https://docs.mongodb.org/manual/reference/method/db.collection.createIndex/
See https://docs.mongodb.org/manual/reference/method/db.collection.distinct/
See https://docs.mongodb.org/manual/reference/method/db.collection.drop/
See https://docs.mongodb.org/manual/reference/method/db.collection.dropIndex/
See https://docs.mongodb.org/manual/reference/method/db.collection.dropIndexes/
See https://docs.mongodb.org/manual/reference/method/db.collection.ensureIndex/
Deprecation Notice: Deprecated since version 3.0.0: db.collection.ensureIndex() is now an alias for db.collection.createIndex().
Returns an array of documents.
See https://docs.mongodb.org/manual/reference/method/db.collection.find/
Returns a cursor instead of an array as db.collection.find does.
See https://docs.mongodb.org/manual/reference/method/db.collection.find/
Apply a query and returns one single document.
See https://docs.mongodb.org/manual/reference/method/db.collection.findOne/
See https://docs.mongodb.org/manual/reference/method/db.collection.findAndModify/
See https://docs.mongodb.org/manual/reference/method/db.collection.getIndexes/
See https://docs.mongodb.org/manual/reference/method/db.collection.group/
Deprecation Notice: Deprecated since version 3.4: Mongodb 3.4 deprecates the db.collection.group() method. Use db.collection.aggregate() with the $group stage or db.collection.mapReduce() instead.
See https://docs.mongodb.com/manual/reference/method/db.collection.insert/
See https://docs.mongodb.com/manual/reference/method/db.collection.isCapped/
See https://docs.mongodb.com/manual/reference/method/db.collection.mapReduce/
See https://docs.mongodb.com/manual/reference/method/db.collection.reIndex/
Equivalent to db.collection.remove(query, { justOne: true/fale })
See https://docs.mongodb.com/manual/reference/method/db.collection.remove/
See https://docs.mongodb.com/manual/reference/method/db.collection.remove/
See https://docs.mongodb.com/manual/reference/method/db.collection.runCommand/
See https://docs.mongodb.com/manual/reference/method/db.collection.save/
See https://docs.mongodb.com/manual/reference/method/db.collection.stats/
See https://docs.mongodb.com/manual/reference/method/db.collection.update/
Creates a new ordered bulk. This operation is sync so no await is needed. See Bulk for more details.
Creates a new unordered bulk. This operation is sync so no await is needed. See Bulk for more details.
Get the name of the collection.
Cursor implements readable stream. So you can for example pipe a cursor to a writeable stream.
db.someCollection.findAsCursor()
.pipe(writeableStream)
.on('finish', () => {
console.log('all documents piped to writeableStream');
});See https://docs.mongodb.com/manual/reference/method/cursor.batchSize/
See https://docs.mongodb.com/manual/reference/method/cursor.count/
See https://docs.mongodb.com/manual/reference/method/cursor.explain/
See https://docs.mongodb.com/manual/reference/method/cursor.limit/
See https://docs.mongodb.com/manual/reference/method/cursor.next/
See https://docs.mongodb.com/manual/reference/method/cursor.hasNext/
See https://docs.mongodb.com/manual/reference/method/cursor.foreach/
See https://docs.mongodb.com/manual/reference/method/cursor.map/
Rewinds a cursor.
See https://docs.mongodb.com/manual/reference/method/cursor.skip/
See https://docs.mongodb.com/manual/reference/method/cursor.sort/
See https://docs.mongodb.com/manual/reference/method/cursor.toArray/
https://docs.mongodb.com/manual/reference/method/cursor.close/
See https://docs.mongodb.com/manual/reference/method/db.createUser/
See https://docs.mongodb.com/manual/reference/method/db.dropUser/
See https://docs.mongodb.com/manual/reference/method/db.dropAllUsers/
See https://docs.mongodb.com/manual/reference/method/db.createCollection/
See https://docs.mongodb.com/manual/reference/method/db.getCollectionNames/
See https://docs.mongodb.com/manual/reference/method/db.getCollectionNames/
See https://docs.mongodb.com/manual/reference/method/db.getCollectionInfos/
See https://docs.mongodb.com/manual/reference/method/db.getLastError/
See https://docs.mongodb.com/manual/reference/method/db.getLastErrorObj/
See https://docs.mongodb.com/manual/reference/method/db.runCommand/
See https://docs.mongodb.com/manual/reference/method/db.stats/
See https://docs.mongodb.com/manual/reference/method/db.close/
See https://docs.mongodb.com/manual/reference/method/db.dropDatabase/
Executes a bulk.