Connecting MongoDB with Node.js

Node.js is a popular JavaScript runtime environment, and MongoDB is a flexible NoSQL database. In this tutorial, we will explore how to connect MongoDB with Node.js using the Mongoose library.


Prerequisites:

To follow along with this tutorial, you need the following:

- Node.js installed on your machine

- MongoDB installed locally or access to a MongoDB cluster

- Basic knowledge of JavaScript and Node.js


Step 1: Install Mongoose

1. Open your terminal or command prompt.


2. Run the following command to install Mongoose:

   npm install mongoose


Step 2: Connect to MongoDB

1. Create a new JavaScript file called `connect.js` and open it in your preferred code editor.


2. Require the Mongoose module:


   const mongoose = require('mongoose');



3. Define the MongoDB connection string. If you have MongoDB installed locally, use the following connection string:

  

   const dbURI = 'mongodb://127.0.0.1:27017/mydatabase';

 


   If you are using a MongoDB cluster, replace `mongodb://localhost/mydatabase` with the connection string provided by your cluster.


4. Connect to MongoDB using Mongoose:

   

   mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })

     .then(() => {

       console.log('Connected to MongoDB');

     })

     .catch((err) => {

       console.error('Error connecting to MongoDB:', err);

     });



5. Save the changes to the `connect.js` file.


Step 3: Test the Connection

1. Open your terminal or command prompt.


2. Run the following command to execute the `connect.js` file:


   node connect.js

 


3. Check the console output. If the connection is successful, you should see the message "Connected to MongoDB." Otherwise, an error message will be displayed.


Conclusion:

Congratulations! You have successfully connected MongoDB with Node.js using Mongoose. This allows you to leverage the powerful features of MongoDB within your Node.js applications. You can now proceed to define models, create schemas, and perform CRUD operations using Mongoose.


Example code:



  

const mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/animals', { useNewUrlParser: true, useUnifiedTopology: true, }); const db = mongoose.connection; db.on('error', console.error.bind(console, 'MongoDB connection error:')); db.once('open', () => { console.log('Connected to MongoDB!'); const Animal = mongoose.model('Animal', new mongoose.Schema({ name: String, color: String, weight: Number, })); const newanimal = new Animal({ name: 'rabbit', color: 'white', weight: 20, }); newanimal.save() .then(savedanimal => { console.log('rabbit saved successfully:', savedanimal); // Close the MongoDB connection mongoose.connection.close(); }) .catch(err => { console.error('Error saving rabbit:', err); // Close the MongoDB connection mongoose.connection.close(); }); });



node connect.js

Connected to MongoDB!

animal saved successfully: {

  name: 'rabbit',

  color: 'white',

  weight: 20,

  _id: new ObjectId("64aa38c6f0aa7c866c7dd435"),

  __v: 0

}



Remember to handle errors gracefully and secure your MongoDB connection with appropriate credentials and access controls in a production environment.


Happy coding!



Post a Comment

0 Comments