Ask Your Question
3

How can the connection between nodejs and mongodb be established?

asked 2022-04-08 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-07-28 01:00:00 +0000

nofretete gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-08 11:00:00 +0000

Seen: 8 times

Last updated: Jul 28 '21