Fast way to start with mongodb. Mongoose schema, model and functions ready to manage database, collection and document.
Mongofast is a helper to manage MongoDB database. It can connect/disconnect to the mongo server, create schema and model and save, list, update and delete documents. Also it can delete database and collection and list db collections.
$ npm install --save @mikosoft/mongofast
/*** NodeJS script ***/
const Mongofast = require('@mikosoft/mongofast');
const main = async () => {
// connection
const mo_uri = 'mongodb://user:pass@55.185.161.70:27017/db-name';
const mongofast = new Mongofast();
const Schema = mongofast.Schema;
await mongofast.connect(mo_uri);
const collectionName = 'mongo-test';
// compile 'mongo-testMD' model
const opts = {timestamps: {createdAt: 'created_at', updatedAt: false}};
const moSchema = {
user_id: { type: mongoose.Schema.Types.ObjectId, ref: 'usersMD' },
company: { type: String, required: 'Field "company" is required' },
year: Number,
};
await mongofast.compileModel(collectionName, moSchema, opts);
// take a model
mongofast.useModel(collectionName);
// create new doc
const doc = {
user_id: '65bcc03db8f6dfe919bcc9d0',
company: 'Apple Ltd',
depth: 1971
};
await mongofast.save(doc)
.then(docNew => {
console.log(`New doc saved to ${collectionName} collection:`);
console.log(docNew);
mongofast.disconnect();
});
// disconnection
await mongofast.disconnect();
};
main().catch(console.log);
Other examples are in /tests/ folder.
The library is using generic (empty & not strict) mongoose schema but user can define any schema.
const collection = 'generic';
// options
const opts = {
collection, // default collection
_id: true, // disable _id
id: false, // set virtual id property
autoIndex: true, // auto-create indexes in mognodb collection on mongoose restart
minimize: true, // remove empty objects
// safe: true, // pass errors to callback
strict: false, // values not defined in schema will not be saved in db
validateBeforeSave: true, // validate doc before saving. prevent saving false docs
timestamps: { // create timestamps for each doc 'created_at' & 'updated_at'
createdAt: 'created_at',
updatedAt: 'updated_at'
},
new: true,
// skipVersioning: { myProp: true }, // prevent changing version __v when 'myProp' is updated
// versionKey: '_myV', // replace __v with _myV (not needed in most cases)
};
// mongoose schema
const moSchema = new Schema({}, opts);
Connects to the mongoDB server via mongo URI. Used database is also defined. mongofast.connect('mongodb+srv://user:pass@cluster0-n4qix.mongodb.net/dbname?retryWrites=true&w=majority')
Disconnect from already connected mongoDB server via mongo URI. mongofast.disconnect()
Remove whole database. mongofast.deleteDatabase()
Lists all collections in the database. mongofast.showCollections()
Removes collection from the database. mongofast.deleteCollection('companies')
Compiles mongoose model. Parameter must be valid mongoose schema. The model object is pushed into the "this.compiledModels" array. mongofast.compileModel(moSchema)
Takes model on which operations will be performed. It defines on which collection documents will be added, listed, updated, removed ... mongofast.useModel(collectionName)
Adds document in collection. Mongoose save function is used. mongofast.save({x: 23, y: 'something'})
Adds document in collection. Parameter can be a single object or array of objects. Mongoose create function is used. mongofast.add({x: 23, y: 'something'}) mongofast.add([{x: 23, y: 'something'}, {x: 25, y: 'aaa'}]) - database called two times
Bulk insertions. While add() will send multiple db requests for every doc, this method will call database only once. Mongoose create function is used.
const insOpts = {
ordered: false, // (true) if true, will fail fast on the first error encountered and don't execute the remaining writes
rawResult: true, // (false) will return inserted docs
lean: false, // (false) if true skip schema validation
limit: null // (null) limits the number of documents being processed
};
mongofast.insertMulti([{x: 23, y: 'something'}, {x: 25, y: 'aaa'}], insOpts) // database called once
List and count documents from collection by using mongo search query criteria. Mongoose find function is used. mongofast.list({x: {$gt3: 3}}, 5, 0, '-x', '-_id')
List documents from collection by using mongo search query criteria. This is useful for big collections because list() method is using count and is much slower. Mongoose find function is used. mongofast.listFast({x: {$gt3: 3}}, 5, 0, '-x', '-_id')
Fetch one document from collection. Mongoose findOne function is used. mongofast.getOne({x: 3})
Delete just one document. Mongoose findOneAndDelete function is used. mongofast.deleteOne({x: 3})
Delete multiple documents. Mongoose deleteMany function is used. mongofast.deleteMulti({x: {$lt: 5}})
Update one document. Mongoose findOneAndUpdate function is used.
const updOpts = {
new: true, // return updated document as 'result'
upsert: false, // whether to create the doc if it doesn't match (false)
runValidators: false, // validators validate the update operation against the model's schema
strict: false, // values not defined in schema will not be saved in db (default is defined in schema options, and can be overwritten here)
// sort: {created_at: -1} // if multiple results are found, sets the sort order to choose which doc to update
}
mongofast.editOne({x: 3}, {x: 5, y: 'some thing'}, updOpts)
Update multiple documents. Mongoose updateMany function is used. mongofast.editMulti({x: {$lt: 5}}, {y: 22})
Count documents according to the given mongo query. Returned value is a number. Mongoose countDocuments function is used. mongofast.count({x: {$gt: 10}})
The software licensed under MIT.