varun-mongo
v1.2.1
Published
mongodb connection using for personal projects
Downloads
6
Readme
In index.js :
require("dotenv").config("./.env");
async function startServer() {
const { connectToDatabase } = require("varun-mongo");
await connectToDatabase("mongodb://localhost:27017", "database1");
// if connection fails, this will throw error and app will not start
await connectToDatabase("mongodb://localhost:27017", "database2");
...
...
...
...
if (!module.parent) {
app.listen(process.env.PORT || 3000);
console.log("App is up and running on localhost:" + process.env.PORT || 3000);
}
}
startServer();
In other files :
const {getConnection} = require("varun-mongo")
async function(){
const db1 = getConnection("database1")
const user = await db1.collection("users").findOne({});
console.log(user);
}
Do not use like this :
const db1 = require("varun-mongo").getConnection("database1");
async function(){
const user = await db1.collection("users").findOne({});
console.log(user);
}
Connection URI
To connect :
mongo mongodb://<username>:<password>@127.0.0.1:27017/admin
For mongorestore :
mongorestore --uri mongodb://<username>:<password>@127.0.0.1:27017/admin --drop --db <database_name> ./
For mongodump :
mongodump --uri=mongodb://<username>:<password>@127.0.0.1:27017/<database_name>?authSource=admin
Note:
- admin is authentication database name.
- Replace 127.0.0.1 with server IP Address.
- 27017 is default mongodb port.