1import mongoose from 'mongoose'
2
3export const connectDb = async () => {
4 try {
5 await mongoose.connect('mongodb://localhost:27017/test', {
6 useNewUrlParser: true,
7 useUnifiedTopology: true,
8 useCreateIndex: true,
9 })
10 } catch (error) {
11 console.log(error.message)
12 }
13}
1//Import the mongoose module
2var mongoose = require('mongoose');
3
4//Set up default mongoose connection
5var mongoDB = 'mongodb://127.0.0.1/my_database';
6mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
7
8//Get the default connection
9var db = mongoose.connection;
10
11//Bind connection to error event (to get notification of connection errors)
12db.on('error', console.error.bind(console, 'MongoDB connection error:'));
1const mongoose = require('mongoose');
2
3const connectDB = async () => {
4 mongoose
5 .connect('mongodb://localhost:27017/playground', {
6 useCreateIndex: true,
7 useNewUrlParser: true,
8 useUnifiedTopology: true,
9 useFindAndModify: false
10 })
11 .then(() => console.log('Connected Successfully'))
12 .catch((err) => console.error('Not Connected'));
13}
14
15module.exports = connectDB;
1const mongoURI =
2 "mongodb+srv://userTest:<password>@cluster0.hgkll.mongodb.net/myFirstDatabase?authSource=admin&replicaSet=atlas-eu2ek5-shard-0&w=majority&readPreference=primary&appname=MongoDB%20Compass&retryWrites=true&ssl=true";
3mongoose
4 .connect(mongoURI, {
5 useNewUrlParser: true,
6 useUnifiedTopology: true,
7 })
8 .then(() => {
9 // eslint-disable-next-line
10 console.log("Database Connection Established...!");
11 })
12 .catch((err) => {
13 // eslint-disable-next-line
14 console.log("Error: Database connection can not be established...!", err);
15 });
16
1mongoose.connect('mongodb://localhost:27017/test', {
2 useMongoClient: true,
3 connectTimeoutMS: 1000
4})
1mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true});