How to Insert Data in MongoDB using Node.js

I'd like to walk you through the process of inserting data into MongoDB using Node.js. MongoDB is a flexible and popular NoSQL database, and Node.js is an excellent platform for building scalable and efficient server-side applications.

Whether you're developing a web application, a RESTful API, or any other backend system, knowing how to insert data into MongoDB is a fundamental skill.

In this tutorial, I'll guide you step by step on how to connect to a MongoDB server, select a database, and insert data into a collection. You'll learn how to insert both single documents and multiple documents, making your application capable of handling various data insertion scenarios.

Let's dive into the world of MongoDB and Node.js and start inserting data seamlessly into our database.

To insert data into MongoDB using Node.js, you can use the official MongoDB driver for Node.js, known as mongodb (or mongodb-core). Here's a step-by-step guide on how to insert data into MongoDB using Node.js.

Prerequisites:

  1. Ensure you have Node.js installed on your system.

  2. Install the mongodb package using npm or yarn

npm install mongodb
# or
yarn add mongodb

 

Step 1: Import the MongoDB Client

First, you need to import the MongoDB client and connect to your MongoDB server.

const { MongoClient } = require('mongodb');

// Replace 'mongodb://localhost:27017/' with your MongoDB connection string
const uri = 'mongodb://localhost:27017/';

// Create a new MongoClient instance
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

// Connect to the MongoDB server
client.connect().then(() => {
  console.log('Connected to MongoDB');
}).catch(err => {
  console.error('Error connecting to MongoDB:', err);
});

 

Step 2: Select a Database

Choose the database where you want to insert your data. If the database does not exist, MongoDB will create it for you when you first insert data.

const dbName = 'mydatabase'; // Replace with your desired database name
const db = client.db(dbName);

 

Step 3: Insert Data

Insert a Single Document:

To insert a single document (an object) into a collection, use the insertOne() method.

const collectionName = 'mycollection'; // Replace with your desired collection name
const collection = db.collection(collectionName);

// Define the document you want to insert
const document = {
  name: 'John Doe',
  email: 'johndoe@example.com',
  age: 30
};

// Insert the document into the collection
collection.insertOne(document, (err, result) => {
  if (err) {
    console.error('Error inserting document:', err);
  } else {
    console.log('Inserted ID:', result.insertedId);
  }

  // Close the MongoDB connection
  client.close();
});

Insert Multiple Documents:

To insert multiple documents (an array of objects) into a collection, use the insertMany() method.

const collectionName = 'mycollection'; // Replace with your desired collection name
const collection = db.collection(collectionName);

// Define an array of documents you want to insert
const documents = [
  {
    name: 'Alice',
    email: 'alice@example.com',
    age: 25
  },
  {
    name: 'Bob',
    email: 'bob@example.com',
    age: 35
  }
];

// Insert the documents into the collection
collection.insertMany(documents, (err, result) => {
  if (err) {
    console.error('Error inserting documents:', err);
  } else {
    console.log('Inserted IDs:', result.insertedIds);
  }

  // Close the MongoDB connection
  client.close();
});

Make sure to replace 'mydatabase' and 'mycollection' with your actual database and collection names.

The insertOne() and insertMany() methods will provide information about the inserted documents, including their unique IDs. Finally, don't forget to close the MongoDB connection after inserting data.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS