nodejs
  1. nodejs-mongodb-insert

Node.js MongoDB Insert

In this tutorial, you'll learn how to insert data into MongoDB using Node.js. We'll use the MongoDB Node.js driver to interact with the MongoDB database.

Syntax

The basic syntax to insert data into a MongoDB collection using Node.js is as follows:

const MongoClient = require('mongodb').MongoClient;

MongoClient.connect(url, function(err, db) {
  const collection = db.collection(collectionName);

  collection.insertOne(document, function(err, result) {
    // code to execute after insertion
  });
});

Here, we use the insertOne() method to insert a single document into the specified collection.

Example

Let's create a simple example to insert data into a users collection:

const MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017', function(err, client) {
  if (err) throw err;
  console.log('Connected to MongoDB');

  const db = client.db('mydb');
  const collection = db.collection('users');

  const user = { name: 'John Doe', email: 'johndoe@example.com' };
  collection.insertOne(user, function(err, result) {
    if (err) throw err;
    console.log('User inserted successfully');
    client.close();
  });
});

Here, we connect to the MongoDB database running on localhost, and insert a user document into the users collection. The insertOne() method takes two arguments: the document to insert, and a callback function to execute after insertion.

Output

When we run the above example, we should see the following output:

Connected to MongoDB
User inserted successfully

This indicates that the data was successfully inserted into the MongoDB collection.

Explanation

In the example above, we use the MongoDB Node.js driver to connect to the local MongoDB server and the mydb database. We then insert a user document into the users collection using the insertOne() method, which takes a document as its argument and inserts it into the collection. The document is defined as a plain JavaScript object with name and email fields.

Use

Inserting data into a MongoDB collection is a fundamental operation you'll perform when building a Node.js application with a MongoDB database. You can use insertOne() to insert a single document, or insertMany() to insert multiple documents.

Important Points

  • Make sure to properly handle errors when inserting data into MongoDB.
  • Ensure that the document object is in the proper format expected by MongoDB.
  • MongoDB will automatically create a collection if it does not exist when inserting a document.

Summary

In this tutorial, we discussed how to insert data into MongoDB using Node.js. We looked at the syntax for inserting a document into a collection and how to handle errors. We also provided an example of how to insert a user document into a users collection. With this knowledge, you can now insert data into a MongoDB collection from a Node.js application.

Published on: