How to Insert Data into MongoDB with Node.js and Mongoose

2020/7/113 min read
bookmark this
Responsive image

This blog will show a tutorial about how to insert data into MongoDB by using Node.js with Mongoose. Mongoose is the Object Data Modeling library for MongoDB and Node.js. It provides functions for schema, query building, and more. If you don't use Mongoose to access MongoDB with Node.js, then you can use the MongoDB package for Node.js directly. 

Get Start

First, initialize a new npm package, we'll create a new package and new file, and add our code for how to insert data to MongoDB.

npm init -y

Next, let's install the mongoose package, this will be the only package we'll use for this tutorial. 

npm install --save mongoose

Create an index.js, we'll add our code to this file to connect to MongoDB and insert data to the Database.

Connect to the MongoDB

Now, the following is a sample code to connect to MongoDB. Assume you already set up MongoDB at your local and has a database as your-database.

const {connect} = require('mongoose');

connect('mongodb://localhost:27017/your-database')
.then(() => {
    console.info('connect successfully')
})
.catch(() => {
    console.error('connection error');
});

Defined MongoDB Schema

Here, we'll define our collection in MongoDB, the collection name will be my-collection-name.

let localModel = new Schema({
    key: {
        type: String
    },
    value: {
        type: String
    },
    culture: {
        type: String
    }
})

let localSchema = model('localization', localModel, 'my-collection-name');

Insert new data into MongoDB

Now, this is the final step we'll insert new data into the collection, we'll use insertMany. after this code it should insert new data into the collection my-collection-name.

localSchema.insertMany({
    key: 'test-key',
    value: 'key description',
    culture: 'en-US'
}).then(function() {
    console.info('insert new data successfully')
}).catch(function() {
    console.error('has error when insert new data');
})

Insert Data to MongoDB by using mongoose.create

Another way to insert into data is following, but then which one is better? Should I use insert or create. 

const createAsync = async() => {
    await localSchema.create({
        key: 'test-key-2',
        value: 'key2 description',
        culture: 'en-US'
    });    
}

createAsync();

So, looks like it is better to use mongoose.insert because it's faster and less issue. So I did some research by insert 100,000 records into MongoDB.

When I execute the following record on my macOS, the insert-timer's time was 11922.764ms. 

const createTestMillionAsync = async() => {
    console.time('insert-timer')
    let testTargetList = [];
    for (let index = 0; index < 100000; index++) {
    
        testTargetList.push({
            key: `test-key-${index}`,
            value: `my test value : ${index}`,
            culture: 'en-US'
        });    
    
    }
    
    await localSchema.insertMany(testTargetList);

    console.timeEnd('insert-timer');
}

createTestMillionAsync();

However, when I tried following 100,000 records with creating I was getting timed out error, the default connection time out is 10000ms.

const createTestMillionAsync = async(roopLimit) => {
    let timerName = `insert-timer-${roopLimit}`;
    console.time(timerName)
    let testTargetList = [];
    for (let index = 0; index < roopLimit; index++) {
    
        testTargetList.push({
            key: `test-key-${index}`,
            value: `my test value : ${index}`,
            culture: 'en-US'
        });    
    
    }
    
    await localSchema.insertMany(testTargetList);

    console.timeEnd(timerName);
}

createTestMillionAsync(100000);

So I extend the connectionTimeout from 10000 to 50000, re-run as following combination, you can see that insertMany are 7 times faster than create. 

Records mongoose.create mongoose.insertMany
100000 75261.921ms  11869.793.ms
500000 Error: Javascript heap out of memory 61775.343ms

Conclusion

Above is how you can insert new data into MongoDB with Node.js with Mongoose. Looks like it's better to use InsertMany for better performance.