Connecting MongoDB with Node.js: A Guide to Using MongoDB and Mongoose
MongoDB is a popular NoSQL database that provides a flexible and scalable solution for storing data. In this guide, we'll walk you through how to connect MongoDB with a Node.js application using two approaches:
mongoosemongodb
Understanding MongoDB.
Before diving into the implementation, let's briefly understand what MongoDB is. MongoDB stores data in a JSON-like structure, making it suitable for handling complex and varying data models. Here's an example of data stored in MongoDB's document format:
Install the package:
npm i mongoose- Create a
dbConnection.jsfile in theconfigfolder:
- Create a
// Create a dbConnection file in config folder const mongoose = require('mongoose'); const options= { useNewUrlParser: true, useUnifiedTopology: true, family :4 // For windows only no need to use it for Linux/Mac } const URL = "mongodb://localhost:27017/playerDB"; const dbConnection = mongoose.connect(URL, options); dbConnection.then(() => { console.log('connection established'); }).catch(err => console.log('connection error',err)) module.exports = dbConnection;3.Define a schema for the players collection in a
playerModel.jsfile:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const playerSchema = new Schema({
displayName: String,
age: Number,
hobbies: Array
});
const playerModel = mongoose.model('playerModels', playerSchema);
module.exports = playerModel;
Using MongoDB Package Alternatively, you can connect to MongoDB using the mongodb package:
- Install the package:
npm i mongodb
Create a connection using the mongodb package:
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const dbName = 'myProject';
async function main() {
try {
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// Perform operations on the collection here
return 'done.';
} catch (error) {
console.error(error);
} finally {
client.close();
}
}
main()
.then(console.log)
.catch(console.error);
In this guide, we explored two ways to connect MongoDB with Node.js: using the mongoose package for a structured schema and the mongodb package for a more direct approach. Both approaches offer flexibility based on your project's requirements.
I hope you found this blog useful. If so, please consider sharing it with your friends and I would appreciate your feedback. You can also reach out to me on Twitter at @lalitaswal2, and I would be happy to hear your thoughts.
![Common Interview Questions for Frontend Developers [GitHub repo with interview questions]](/_next/image?url=https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1767864261518%2F95d24406-007a-4b35-86f6-7598514fb7b7.png&w=3840&q=75)