Using MongoDB with Node.js requires the usage of either a MongoDB driver or an Object Data Modeling (ODM) library like Mongoose that wraps the driver. Once you have those set up, you can establish a connection and interact with your database. Generally speaking, you’ll need to perform the following steps:
Here is a simple example of establishing a connection and performing CRUD operations with the MongoDB Node.js driver:
Step 1: Installation
Before we start, make sure Node.js and MongoDB are installed in your system. You can download Node.js from https://nodejs.org/ and MongoDB from https://www.mongodb.com/.
Then install the MongoDB Node.js driver via npm:
```
npm install mongodb
```
Step 2: Connecting to MongoDB
Start your MongoDB server and create a new .js file and enter the following:
```
const MongoClient = require(‘mongodb’).MongoClient;
const url = ‘mongodb://localhost:27017’;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log(“Database created!”);
db.close();
});
```
In the callback function we first check if there is an error. If there is, we throw the error; if there isn’t we do what we came to do.
Step 3: Creating a database
To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create.
```
const MongoClient = require(‘mongodb’).MongoClient;
const url = ‘mongodb://localhost:27017/mydb’; // mydb is the name of db.
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log(“Database created!”);
db.close();
});
```
Step 4: Creating a collection
MongoDB uses collections to store data. You could liken them to tables in relational databases.
```
const MongoClient = require(‘mongodb’).MongoClient;
const url = ‘mongodb://localhost:27017/’;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db(“mydb”);
dbo.createCollection(“customers”, function(err, res) {
if (err) throw err;
console.log(“Collection created!”);
db.close();
});
});
```
Step 5: Inserting documents
To insert data into MongoDB collection, you need to use insertOne() method.
```
const MongoClient = require(‘mongodb’).MongoClient;
const url = “mongodb://localhost:27017/”;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db(“mydb”);
var myobj = { name: “Company Inc”, address: “Highway 37” };
dbo.collection(“customers”).insertOne(myobj, function(err, res) {
if (err) throw err;
console.log(“1 document inserted”);
db.close();
});
});
```
Step 6: Querying documents
```
var query = { address: “Park Lane 38” };
dbo.collection(“customers”).find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
```
Step 7: Updating documents
You update documents in a collection by using the “updateOne()” method:
```
var myquery = { address: “Valley 345” };
var newvalues = { $set: {name: “Mickey”, address: “Canyon 123” } };
dbo.collection(“customers”).updateOne(myquery, newvalues, function(err, res) {
if (err) throw err;
console.log(“1 document updated”);
db.close();
});
```
Step 8: Deleting documents
You can delete records, or documents as it’s called in MongoDB, by using the “deleteOne()” method.
```
var myquery = { address: ‘Mountain 21’ };
dbo.collection(“customers”).deleteOne(myquery, function(err, obj) {
if (err) throw err;
console.log(“1 document deleted”);
db.close();
});
```
Step 9: Closing the connection
Finally, we close the connection to the database after our CRUD operations with db.close().
This code snippet shows basic operations with the MongoDB Node.js driver, there are much more advanced queries and operations that can be done, and libraries such as Mongoose provide a more advanced, schema-based solution to using MongoDB with Node.js.
Additionally, if you’re connecting to a MongoDB instance remotely (like MongoDB Atlas), adjust the connection string (url) as needed.