Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To establish a connection between Node.js and MongoDB, follow these steps:

  1. Install the MongoDB driver for Node.js using npm.

install mongodb --save

  1. Create a MongoDB client object to represent the MongoDB server.
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/myproject';

MongoClient.connect(url, function(err, client) {
  console.log("Connected successfully to server");
  const db = client.db('myproject');

  client.close();
});
  1. Use the MongoClient object to interact with the MongoDB server.
db.collection('users').insertOne({
  name: "John Doe",
  age: 25
}, function(err, result) {
  console.log("Inserted document with _id: " + result.insertedId);
});
  1. Handle errors and close the connection when finished.
client.close(function(err) {
  console.log("Closed MongoDB connection");
});

With these steps, you can establish a connection between Node.js and MongoDB and start performing database operations.