1 | initial version |
To establish a connection between Node.js and MongoDB, follow these steps:
install mongodb --save
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();
});
db.collection('users').insertOne({
name: "John Doe",
age: 25
}, function(err, result) {
console.log("Inserted document with _id: " + result.insertedId);
});
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.