Created
January 27, 2023 06:29
-
-
Save fazaio/36d8d168c81154845579319a67f23a24 to your computer and use it in GitHub Desktop.
NodeJS & MongoDB ( export module connection mongodb, reuseable and clean code)
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 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(); |
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 { 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