Node.js MongoDB Insert

In MongoDB, inserting data into collections is a fundamental operation. Unlike traditional SQL databases, MongoDB is schema-less, meaning you can insert documents with different structures into the same collection without defining a strict table schema beforehand. Using the official Node.js driver, you can efficiently add data as BSON (Binary JSON) documents.

Developer Tip: If you attempt to insert data into a database or collection that doesn't exist yet, MongoDB will automatically create them for you the moment the first document is written.

 

Key Features of Insert Operations

  1. Schema Flexibility: You can insert a single document or multiple documents with varying fields in one operation.
  2. Automatic Indexing: Each document is automatically assigned a unique _id field by MongoDB if you don't provide one. This acts as the primary key.
  3. Write Concerns: You can configure how much acknowledgment you need from the database server before a write is considered successful, which is vital for data integrity.
  4. Batch Performance: The insertMany method reduces the overhead of network round-trips by sending multiple records in a single request.

 

Step 1 Prerequisites

Before writing code, ensure you have a Node.js environment ready. You will need the mongodb package installed in your project folder. If you haven't initialized your project yet, run npm init -y first.

npm install mongodb
Best Practice: Always use the latest version of the MongoDB driver to take advantage of security patches, performance improvements, and the latest ES6+ features like top-level await.

Step 2 Insert a Single Document

The insertOne method is your primary tool for adding a single object to your collection. This is commonly used for tasks like user registration or saving a specific application setting.

Example Code

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

// Connection URL - use environment variables in production!
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'mydatabase';

async function insertSingleDocument() {
  const client = new MongoClient(url);

  try {
    // Connect to the MongoDB server
    await client.connect();
    console.log('Connected successfully to server');
    
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Define the document to insert
    const newUser = { 
        name: 'Alice', 
        age: 28, 
        email: '[email protected]',
        createdAt: new Date() 
    };

    // Perform the insert operation
    const result = await collection.insertOne(newUser);
    
    // The result object tells us the ID that MongoDB generated
    console.log('Document inserted with _id:', result.insertedId);
  } catch (err) {
    console.error('Insert failed:', err);
  } finally {
    // Always close the connection to avoid memory leaks
    await client.close();
  }
}

insertSingleDocument().catch(console.error);

Output:

Connected successfully to server
Document inserted with _id: 61b0fcab12c5ae23f89e7a12
Common Mistake: Forgetting to use await or .then() when calling insertOne. Since database operations are asynchronous, failing to wait for the operation will lead to "Race Conditions" where your code proceeds before the data is actually saved.

Step 3 Insert Multiple Documents

When you have a list of data such as migrating records from a CSV file or bulk-uploading products the insertMany method is significantly faster than looping through an array and calling insertOne repeatedly.

Example Code

async function insertMultipleDocuments() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Array of documents to insert
    const users = [
      { name: 'Bob', age: 32, role: 'Admin' },
      { name: 'Charlie', age: 45, role: 'User' },
      { name: 'Diana', age: 29, role: 'Editor' }
    ];

    const result = await collection.insertMany(users);
    
    console.log(`${result.insertedCount} documents were inserted.`);
    console.log('Inserted IDs:', result.insertedIds);
  } finally {
    await client.close();
  }
}

insertMultipleDocuments().catch(console.error);

Output:

3 documents were inserted.
Inserted IDs: { '0': 61b0fcab..., '1': 61b0fcab..., '2': 61b0fcab... }
Watch Out: By default, insertMany is "ordered." This means if the 3rd document in a list of 10 fails (e.g., due to a validation error), MongoDB will stop and not attempt to insert the remaining 7. You can change this by passing { ordered: false } as an option.

Step 4 Verify Inserted Data

After running your Node.js scripts, it is good practice to verify that the data reached the database correctly. You can do this via the command line or a GUI tool.

  • Via MongoDB Compass: Open the application, connect to localhost:27017, and navigate to mydatabase > users.
  • Via Mongosh (Shell): Run the following commands in your terminal:
# Enter the shell
mongosh

# Switch to the database
use mydatabase

# Find all documents in the 'users' collection
db.users.find().pretty()

Step 5 Handle Duplicate Keys

The _id field is unique. While MongoDB usually generates an ObjectId for you, you can provide your own custom _id. However, if you try to insert a document with an _id that already exists in the collection, the driver will throw a MongoServerError.

Example Code

async function handleDuplicateKey() {
  const client = new MongoClient(url);

  try {
    await client.connect();
    const db = client.db(dbName);
    const collection = db.collection('users');

    // Manually setting a numeric _id
    const doc = { _id: 101, name: 'David', age: 29 };
    
    await collection.insertOne(doc);
    console.log('First insert successful.');

    // Attempting to insert the same _id again
    await collection.insertOne({ _id: 101, name: 'Emma', age: 34 });
    
  } catch (error) {
    if (error.code === 11000) {
        console.error('Error: A document with this ID already exists!');
    } else {
        console.error('An unexpected error occurred:', error.message);
    }
  } finally {
    await client.close();
  }
}

handleDuplicateKey().catch(console.error);

Output:

First insert successful.
Error: A document with this ID already exists!
Best Practice: Unless you have a specific reason to use a custom ID (like a pre-existing SKU or employee number), let MongoDB generate the ObjectId. It is designed to be highly unique across distributed systems and includes a timestamp.

 

Summary

Mastering insertOne and insertMany is the foundation of building data-driven applications with Node.js and MongoDB. By leveraging the flexible nature of BSON documents, you can quickly evolve your data structures without complex migrations. Always remember to handle potential errors like duplicate keys and ensure your database connections are closed properly to keep your application performant.