xxxxxxxxxx
const MONGO_URI = "mongodb-uri"
import mongoose from 'mongoose';
const connectMongo = async () => {
try{
const { connection } = await mongoose.connect(MONGO_URI)
if(connection.readyState == 1){
console.log("Database Connected")
}
}catch(errors){
return Promise.reject(errors)
}
}
export default connectMongo;
xxxxxxxxxx
const {
MongoClient
} = require("mongodb");
// Connection URI
const uri =
"mongodb+srv://demo:demo@cluster23.q3323m24t53wj.mongodb.net/?retryWrites=true&w=majority";
// Create a new MongoClient
const client = new MongoClient(uri);
async function main() {
try {
await client.connect();
await listDatabases(client);
console.log("Connected successfully to Mongo server");
} catch (e) {
console.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
async function listDatabases(client) {
const databasesList = await client.db().admin().listDatabases();
console.log("Databases:")
databasesList.databases.forEach(db => {
console.log(`- ${db.name}`);
});
}
xxxxxxxxxx
1 mongo # connects to mongodb://127.0.0.1:27017 by default
2 mongo --host <host> --port <port> -u <user> -p <pwd> # omit the password if you want a prompt
3 mongo "mongodb://192.168.1.1:27017"
4 mongo "mongodb+srv://cluster-name.abcde.mongodb.net/<dbname>" --username <username> # MongoDB Atlas
xxxxxxxxxx
const {
MongoClient
} = require("mongodb");
// Connection URI
const uri =
"mongodb+srv://demo:demo@cluster0we.q3ewewmt5wj.mongodb.net/?retryWrites=true&w=majority";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("admin").command({
dbStats: 1,
});
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
xxxxxxxxxx
const { MongoClient } = require("mongodb");
const connectionString = process.env.ATLAS_URI;
const client = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
let dbConnection;
module.exports = {
connectToServer: function (callback) {
client.connect(function (err, db) {
if (err || !db) {
return callback(err);
}
dbConnection = db.db("sample_airbnb");
console.log("Successfully connected to MongoDB.");
return callback();
});
},
getDb: function () {
return dbConnection;
},
};
Connect to mongoDB database
xxxxxxxxxx
const { MongoClient } = require("mongodb");
// Connection URI
const uri = "<connection string uri>";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
xxxxxxxxxx
const start = async () => {
if (!process.env.DB_URI) {
throw new Error('auth DB_URI must be defined');
}
try {
await mongoose.connect(process.env.DB_URI!, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log('Server connected to MongoDb!');
} catch (err) {
throw new DbConnectionError();
console.error(err);
}
const PORT = process.env.SERVER_PORT;
app.listen(PORT, () => {
console.log(`Server is listening on ${PORT}!!!!!!!!!`);
});
};
start();
Run code snippetHide results