whathetech Database,Mongodb,node.js Mongoose Insert Document using insertMany using Node.JS

Mongoose Insert Document using insertMany using Node.JS

Continuing from our previous post http://whatthetech.co/mongodb-with-nodejs-using-mongoose-connection/, let us now see how we can use insertMany to add new documents to our youtube collection.
We will use postman to post request.

To begin with, lets add a new REST end point to accept documents that needs to be inserted.

//server.js      
app.post('/insertmany', function(req, res) {
            dao.insertMany(data).then(response=>{
                console.log('/updateSchema');
                res.status(200).send('Inserted new doc');
            })
            .catch(err=>{
                console.log(err);
                res.status(400).send('Failed to insert');
            });
        });

As you can see, we are calling dao.insertMany. So, lets open dao.js and add this new function

{
   "_id": "1001",
   "channelId": "1001",
    "title": "Inserting using insertMany",
    "description": "Inserting using insertMany description",
    "thumbnails": {
    },
    "categoryId": "0",
    "viewCount": "1",
    "likeCount": "2",
    "dislikeCount": "3",
    "favoriteCount": "4",
    "commentCount": "5"
  }

We will now check if the data has actually been inserted in mongodb. Open mongo sheel and follow the below steps:

home@home-home-1:~$ mongo localhost
MongoDB shell version: 3.2.17
connecting to: localhost
Server has startup warnings: 
2017-10-26T20:05:08.471+0530 I CONTROL  [initandlisten] 
2017-10-26T20:05:08.471+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-10-26T20:05:08.471+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-10-26T20:05:08.471+0530 I CONTROL  [initandlisten] 
2017-10-26T20:05:08.471+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-10-26T20:05:08.471+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-10-26T20:05:08.471+0530 I CONTROL  [initandlisten] 
show dbs
example  0.000GB
local    0.000GB
test     0.000GB
use example
switched to db example
show collections
youtubes
db.youtubes.find({})
{ "_id" : "1001", "__v" : 0, "commentCount" : 5, "favoriteCount" : 4, "dislikeCount" : 3, "likeCount" : 2, "viewCount" : 1, "duration" : 0, "categoryId" : 0, "defaultLanguage" : "", "description" : "Inserting using insertMany description", "title" : "Inserting using insertMany", "channelId" : "1001" }

Let’s now try to insert 2 docs using the same API and see what happens.
I will be sending the below docs using postman

[{
   "_id": "1003",
   "channelId": "1003",
    "title": "Inserting using insertMany",
    "description": "Inserting using insertMany description",
    "thumbnails": {
    },
    "categoryId": "0",
    "viewCount": "1",
    "likeCount": "2",
    "dislikeCount": "3",
    "favoriteCount": "4",
    "commentCount": "5"
  },
  {
   "_id": "1004",
   "channelId": "1004",
    "title": "Inserting using insertMany",
    "description": "Inserting using insertMany description",
    "thumbnails": {
    },
    "categoryId": "0",
    "viewCount": "1",
    "likeCount": "2",
    "dislikeCount": "3",
    "favoriteCount": "4",
    "commentCount": "5"
  }]

Let us check in the shell if its actually inserted

 db.youtubes.find({})
{ "_id" : "1001", "__v" : 0, "commentCount" : 5, "favoriteCount" : 4, "dislikeCount" : 3, "likeCount" : 2, "viewCount" : 1, "duration" : 0, "categoryId" : 0, "defaultLanguage" : "", "description" : "Inserting using insertOne description", "title" : "Inserting using insertOne", "channelId" : "1001" }
{ "_id" : "1002", "__v" : 0, "commentCount" : 5, "favoriteCount" : 4, "dislikeCount" : 3, "likeCount" : 2, "viewCount" : 1, "duration" : 0, "categoryId" : 0, "defaultLanguage" : "", "description" : "Inserting using insertOne description", "title" : "Inserting using insertOne", "channelId" : "1001" }
{ "_id" : "1003", "__v" : 0, "commentCount" : 5, "favoriteCount" : 4, "dislikeCount" : 3, "likeCount" : 2, "viewCount" : 1, "duration" : 0, "categoryId" : 0, "defaultLanguage" : "", "description" : "Inserting using insertMany description", "title" : "Inserting using insertMany", "channelId" : "1003" }
{ "_id" : "1004", "__v" : 0, "commentCount" : 5, "favoriteCount" : 4, "dislikeCount" : 3, "likeCount" : 2, "viewCount" : 1, "duration" : 0, "categoryId" : 0, "defaultLanguage" : "", "description" : "Inserting using insertMany description", "title" : "Inserting using insertMany", "channelId" : "1004" }

You can see that id 1003 and 1004 has been inserted.

What would happen if we try to insert a doc with the same ID which is already present in the DB. Lets try it out. Send the previous postman request again and check the response on your nodejs terminal

[ { _id: '1003',
    channelId: '1003',
    title: 'Inserting using insertMany',
    description: 'Inserting using insertMany description',
    thumbnails: {},
    categoryId: '0',
    viewCount: '1',
    likeCount: '2',
    dislikeCount: '3',
    favoriteCount: '4',
    commentCount: '5' },
  { _id: '1004',
    channelId: '1004',
    title: 'Inserting using insertMany',
    description: 'Inserting using insertMany description',
    thumbnails: {},
    categoryId: '0',
    viewCount: '1',
    likeCount: '2',
    dislikeCount: '3',
    favoriteCount: '4',
    commentCount: '5' } ]
{ MongoError: E11000 duplicate key error collection: example.youtubes index: _id_ dup key: { : "1003" }
    at Function.MongoError.create (/home/vinod/projects/whatthetech/mongoose/node_modules/mongodb-core/lib/error.js:31:11)
    at toError (/home/vinod/projects/whatthetech/mongoose/node_modules/mongodb/lib/utils.js:139:22)
    at /home/vinod/projects/whatthetech/mongoose/node_modules/mongodb/lib/collection.js:668:23
    at handleCallback (/home/vinod/projects/whatthetech/mongoose/node_modules/mongodb/lib/utils.js:120:56)
    at resultHandler (/home/vinod/projects/whatthetech/mongoose/node_modules/mongodb/lib/bulk/ordered.js:421:14)
    at /home/vinod/projects/whatthetech/mongoose/node_modules/mongodb-core/lib/connection/pool.js:469:18
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  name: 'MongoError',
  message: 'E11000 duplicate key error collection: example.youtubes index: _id_ dup key: { : "1003" }',
  driver: true,
  code: 11000,
  index: 0,
  errmsg: 'E11000 duplicate key error collection: example.youtubes index: _id_ dup key: { : "1003" }',
  getOperation: [Function],
  toJSON: [Function],
  toString: [Function] }

It clearly tells you with an error code 11000 that the key is duplicate and that the document was not insterted.

Tags: , , ,