The connect()
method provided by the Mongoose supports both JavaScript promises and async-await syntax.
The following example demonstrates how you can use promises to create a connection with MongoDB:
const mongoose = require('mongoose');
const server = '127.0.0.1:27017'; // REPLACE WITH YOUR OWN SERVER
const database = 'test'; // REPLACE WITH YOUR OWN DB NAME
mongoose.connect(`mongodb://${server}/${database}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
}).then(() => {
console.log('MongoDB connected!!');
}).catch(err => {
console.log('Failed to connect to MongoDB', err);
});
To use async-await syntax, you need to write an asynchronous function, as shown below:
const mongoose = require('mongoose');
const server = '127.0.0.1:27017'; // REPLACE WITH YOUR OWN SERVER
const database = 'test'; // REPLACE WITH YOUR OWN DB NAME
const connectDB = async () => {
try {
await mongoose.connect(`mongodb://${server}/${database}`, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
});
console.log('MongoDB connected!!');
} catch (err) {
console.log('Failed to connect to MongoDB', err);
}
};
connectDB();
Take a look at this article to learn more about setting up a MongoDB connection in Node.js.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.