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;
1mongoose.connect('mongodb://localhost:27017/test', {
2 useMongoClient: true,
3 connectTimeoutMS: 1000
4})
1// getting-started.js
2const mongoose = require('mongoose');
3mongoose.connect("mongodb://localhost:27017/name", { useUnifiedTopology: true, useNewUrlParser: true });
1
2//connect with mongodb
3mongoose.connect('mongodb://localhost:27017/your_db_name', {useNewUrlParser: true});
4//you can also specify with user and pass
5mongoose.connect('mongodb://username:password@host:port/database?options...', {useNewUrlParser: true});
6//or goto docs https://mongoosejs.com/docs/connections.html