Connecting MongoDB with Node.js: A Guide to Using MongoDB and Mongoose

·

2 min read

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:

mongoose
mongodb
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:

  1. Install the package:

     npm i mongoose
    
    1. Create a dbConnection.js file in the config folder:
  1. 
       // 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.js file:

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:

  1. 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.