Member-only story
Using MongoDB with Mongoose — Connections
3 min readJan 15, 2021
To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.
In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.
Connections
We can connect to a MongoDB database with Mongoose.
To do that, we write:
const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
console.log('connected')
});
We connect to the server with the URL and the test
collection name.
Operation Buffering
We can start using the models immediately without waiting fir Mongoose to establish a connection.
So we can write:
const mongoose = require('mongoose');
const connection = "mongodb://localhost:27017/test";
mongoose.connect(connection, { useNewUrlParser: true });
const db = mongoose.connection;
db.on('error', () => console.error('connection error:'));
db.once('open', () => {
console.log('connected')
});async function run() {…