Skip to content

Instantly share code, notes, and snippets.

@fazaio
Created January 27, 2023 06:29
Show Gist options
  • Save fazaio/36d8d168c81154845579319a67f23a24 to your computer and use it in GitHub Desktop.
Save fazaio/36d8d168c81154845579319a67f23a24 to your computer and use it in GitHub Desktop.
NodeJS & MongoDB ( export module connection mongodb, reuseable and clean code)
const DB = require("./src/configs/db");
const USERS_COLLECTION = DB.client.db("Tjackrabirawa").collection("users");
const READS_USERS = async () => {
try {
await DB.connectToDB();
let arr = [];
let result = USERS_COLLECTION.find();
await result.forEach((element) => {
arr.push(element);
});
console.log(arr);
} catch (e) {
console.log(e);
}
};
const CREATES_USERS = async (payload) => {
await DB.connectToDB();
let result = await USERS_COLLECTION.insertOne(payload);
console.log(result);
};
// CREATES_USERS({ data: "testing" });
// READS_USERS();
const { MongoClient, ServerApiVersion } = require("mongodb");
const url =
"mongodb+srv://< url here >.jo8pywx.mongodb.net/?retryWrites=true&w=majority";
module.exports = {
client: (client = new MongoClient(url, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverApi: ServerApiVersion.v1,
})),
connectToDB: async () => {
try {
await client.connect();
console.log("connected!");
} catch (err) {
console.log("Err", err);
}
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment