how to install mongodb in node js
To install MongoDB in Node.js, follow these steps:
- Create a new folder for your project and navigate to it in your terminal or command prompt.
- Create a new file called
index.js
in the folder. - Open the
index.js
file and copy the following code into it: ```javascript const MongoClient = require("mongodb").MongoClient; const uri = "YOUR_MONGODB_URI"; // Replace this with your MongoDB Atlas URI const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect((err) => { if (err) throw err; console.log("Connected to MongoDB");
// Perform database operations here
client.close();
});
Replace `"YOUR_MONGODB_URI"` with your actual MongoDB Atlas URI. This URI is provided by MongoDB Atlas when you create a new cluster.
4. Save the `index.js` file.
5. Open your terminal or command prompt and navigate to the project folder.
6. Run the following command to install the MongoDB Node.js driver:
npm install mongodb
This command will install the necessary dependencies for connecting to MongoDB in your Node.js project.
7. After the installation is complete, run the following command to execute your `index.js` file:
node index.js
```
This command will run your Node.js application and connect to MongoDB using the provided URI.
8. If everything is set up correctly, you should see the message "Connected to MongoDB" in your terminal or command prompt.
Please note that the code provided is a basic example for connecting to MongoDB in Node.js. You can perform various database operations within the client.connect
callback function. Make sure to replace "YOUR_MONGODB_URI"
with your actual MongoDB Atlas URI to establish a connection.