Skip to content

Instantly share code, notes, and snippets.

@dmdboi
Last active January 8, 2021 03:40
Show Gist options
  • Save dmdboi/3f1f87f381c76d1992f4516c41826c68 to your computer and use it in GitHub Desktop.
Save dmdboi/3f1f87f381c76d1992f4516c41826c68 to your computer and use it in GitHub Desktop.
A simple MongoDB wrapper for an Express server.
let DB_URL = ""
let DB_NAME = ""
const { MongoClient } = require("mongodb");
const client = new MongoClient(DB_URL);
let mongo = {
db: null,
collections: {},
};
const connect = async function () {
await client.connect();
mongo["db"] = await client.db(DB_NAME);
mongo["collections"] = await client
.db(global.DB_NAME)
.listCollections()
.toArray();
return mongo;
};
module.exports = { connect, mongo };
const { mongo } = require("./mongo");
const db = mongo.db;
// collection - The name of the collection to perform operation on
// body - req.body or an object with data to insert/update in a table
// query - Filter to find document in the table i.e { username: "DMDBOI" }
const database = {
create: async function (collection, body) {
let document = await db
.collection(collection)
.insertOne(body, { safe: true });
return document;
},
find: async function (collection, query) {
let document = await db.collection(collection).findOne(query);
return document;
},
update: async function (collection, query, body) {
let document = await db
.collection(collection)
.findOneAndUpdate(query, { $set: body }, { safe: true });
return document;
},
delete: async function (collection, query) {
let document = await db
.collection(collection)
.deleteOne(query, { safe: true });
return document;
},
};
module.exports = database;
@dmdboi
Copy link
Author

dmdboi commented Jan 8, 2021

Used to reduce code needed to interact with MongoDB using Mongoose.
This removes the need to import models and write individual CRUD operations per collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment