Last active
January 8, 2021 03:40
-
-
Save dmdboi/3f1f87f381c76d1992f4516c41826c68 to your computer and use it in GitHub Desktop.
A simple MongoDB wrapper for an Express server.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.