02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School

mongoDB Driver in NodeJS

MongoDB Driver in Node.js

Welcome to this tutorial, where we'll guide you through integrating a MongoDB driver into a Node.js environment. By the end of this guide, you'll be well-equipped to handle MongoDB connections, update collections, and use bulk operations—all within Node.js. Let's jump right in!

1. Setting Up Your Project

First, initialize your Node.js project. We'll use npm to create the initial setup.

npm init -y

This command will create a default package.json file for our project. Next, we need to install the MongoDB driver. Instead of using the official mongodb driver, we'll use the mongojs driver for simplicity.

npm install mongojs --save

Note: In recent projects, it's recommended to use the official MongoDB driver, as it is actively maintained and updated with the latest features. The syntax and feature set may vary slightly, but it generally offers better support and performance.

2. Connecting to the Database

Once you have installed mongojs, it's time to connect to your MongoDB database. Open or create your index.js file and add the following code:

const mongojs = require('mongojs');

// Set up the database connection
const db = mongojs('mongo_sample', ['users']);

In the above snippet:

  • We're requiring the mongojs package.
  • We're connecting to the mongo_sample database and specifying the users collection, which will reduce overhead by limiting the collections loaded during initialization.

Note: For modern projects, using the MongoClient from the official MongoDB driver allows more robust connection pooling and better support for modern features like transactions.

3. Bulk Operations

The bulk operations feature is useful when you need to perform multiple modifications at once. Let's initialize a bulk operation and add some new users.

const bulk = db.users.initializeOrderedBulkOp();

bulk.insert({ name: 'Ben', age: 33, height: 181, charmFactor: 5 });
bulk.insert({ name: 'David', age: 29, height: 175, charmFactor: 8 });
bulk.insert({ name: 'Gloria', age: 27, height: 160, charmFactor: 7 });

bulk.execute((err, res) => {
  if (err) {
    console.error('Error executing bulk operation:', err);
  } else {
    console.log('Bulk operation completed successfully:', res);
  }
});

In the above code:

  • We initialize a bulk operation with initializeOrderedBulkOp(). This ensures that the operations are executed in sequence.
  • We're inserting multiple user records.
  • Finally, we call execute() to run the bulk operation and provide a callback to handle errors or log the response.

Important Update: In the official MongoDB driver, bulk operations can be performed using bulkWrite(). It provides more flexibility and an easier syntax.

4. Updating Collections

In this section, we want to update a specific user's age. Let's say Ben is celebrating his birthday, and we need to update his age from 33 to 34.

db.users.update({ name: 'Ben' }, { $set: { age: 34 } }, (err, res) => {
  if (err) {
    console.error('Failed to update Ben's age:', err);
  } else {
    console.log('Ben's age updated successfully:', res);
  }
});
  • We use $set to modify Ben's age property without affecting other fields.
  • This update operation is helpful when you need to make incremental changes instead of overwriting the whole document.

Note: When using the official MongoDB driver, updateOne() and updateMany() are used for similar operations with more consistent support for modern MongoDB features.

5. Removing Records

Suppose we need to delete users under 30 years of age, such as David and Gloria. We can use a conditional delete operation as follows:

db.users.remove({ age: { $lt: 30 } }, (err, res) => {
  if (err) {
    console.error('Error removing users:', err);
  } else {
    console.log('Users removed successfully:', res);
  }
});

In this snippet:

  • We're removing all users whose age is less than 30 using $lt (less than).

Important Update: In the latest versions of MongoDB, the deleteOne() and deleteMany() methods are recommended for greater clarity and more consistent API usage.

6. Callback vs. Asynchronous Programming

Node.js is an asynchronous environment, meaning it does not wait for an operation to complete before moving on. Therefore, most MongoDB interactions are handled using callbacks, as seen in the previous examples. However, modern Node.js applications prefer async/await syntax for better readability.

Here's an example of how you could rewrite the update function using async/await:

async function updateAge() {
  try {
    const res = await db.users.updateAsync({ name: 'Ben' }, { $set: { age: 34 } });
    console.log('Ben's age updated successfully:', res);
  } catch (err) {
    console.error('Failed to update Ben's age:', err);
  }
}

Note: Some drivers require a wrapper or update to support promises natively. It is recommended to use the official driver to fully leverage async/await support.

Conclusion

Congratulations! You've successfully learned how to work with MongoDB in a Node.js environment. We covered installing a MongoDB driver, setting up a connection, performing bulk operations, updating documents, and removing records—all crucial skills for a full-stack developer.

Remember that, while mongojs was a great learning tool in 2016, newer projects should consider adopting the official MongoDB driver for improved support, modern features, and performance. Keep pushing your skills further and happy coding!

Video Transcript

00:00Welcome to the last lecture in this
00:02title and this section.
00:04And I first wanna congratulate you
00:06'cause at this stage you could tap your back
00:08because essentially you're a full stack developer
00:11in this last lecture, which is relatively long.
00:13So we'll keep the introductory points short.
00:16We're gonna pick a Mongo DB driver
00:19and integrate it into our node js.
00:22We're also gonna take that driver for a run showing you how
00:25to use that specific driver within node js.
00:29Last but not least, we're gonna cover one last topic in
00:32MongoDB and that is how do you actually update collections?
00:35It's gonna be the first time that we do it.
00:37And with that said, let's jump right into our last,
00:40last lecture in this title.
00:43On contrary to working with the built in our official driver
00:49of MongoDB, we're not gonna do that
00:51because the official driver, which by the way,
00:54if you'd wanted to set it up,
00:55let me first set up our project with NPM in it, minus y.
00:59We're just gonna do the default.
01:01Once we defaulted
01:02and created our template of our application, I want
01:05to go ahead and install MongoDB driver.
01:08Now I'm not gonna go for the official driver,
01:10which is called Mongo db.
01:12So I'm not gonna install Mongo DB
01:15because I just don't like the driver as much as I like Mongo
01:19js, which is not a nonofficial one.
01:22And we're gonna go ahead and save it into our project.
01:24Let's go ahead and install it.
01:26Now the Mongo JS Co on contrary to the MongoDB tries
01:29to mimic itself as close as it can to the way Mongo works
01:34in its native capacity.
01:36Like we saw it inside
01:38of our Mongo console in all the previous chapters, uh,
01:41lectures in this chapter.
01:43So now that I have MongoDB installed, let's go ahead
01:46and open our index file.
01:48And in the index file I'm gonna go ahead
01:49and call that Mongo js
01:52and I'm gonna require it Mongo js.
01:56There we go. So we required Mongo js.
01:59Now I'm gonna go ahead and I'm gonna set a variable
02:01for our database and I'm gonna go to our Mongo js
02:04and call it and request
02:06for the database that we wish to use.
02:08In this case, we want to continue working with Mongo sample.
02:12And this is not mandatory,
02:15but in the second parameter, let's set in an array
02:18that will have all the different
02:20collections that we're gonna be using.
02:22This is just to reduce the stress on the, on the
02:26behind the scenes so it knows what to expect.
02:29Now, you could also dynamically approach things in this way,
02:32but if you know in advance what you're gonna be using,
02:34you're better off to just call in advance
02:36and say, these are the collections
02:38I'm going to be working with.
02:40This is all we had to do to connect to our database.
02:43Now that we're connected to our database, I want to,
02:46I'm not gonna show you the exact same thing
02:48that we've seen previously.
02:49I wanna continue on to two new topics
02:51and merge them together.
02:53And it'll be up to you to experiment
02:54and play with all the things
02:56that we've done in the previous lectures to see
02:58how do you do them inside no js.
03:01So what I wanna do is I wanna show you a new feature since
03:04Mongo DB 2.6 I believe somewhere around that,
03:07that enables us to do bulk operations.
03:10With bulk operations.
03:11What we really wanna do is we're gonna set
03:13what collection we wanna work with.
03:15And this case we wanna work with our users
03:17and I'm gonna call it in lies ordered
03:22bulk operation.
03:24And lemme just make sure that I typed it correctly
03:27'cause this is a massively big word and I have,
03:31and I'm gonna open close bracket, round bracket
03:34and I've just created a bulk operator.
03:36Now these, this bulk operator, what it lets me do,
03:39it enables me to add things
03:42or make a list of the things that I want
03:44to add or change or modify.
03:46And then when I'm done, only trigger an operation once.
03:49This is very effective.
03:50'cause then we're now going back and forth a lot of times
03:52to our, to our database.
03:54Now even before I do that, I wanna make sure
03:56that my database is cleared out.
03:58So let me go into our console
04:00and let's check what DB we're in.
04:02Okay, so we're in the Mongo db
04:03and I want to, uh, let me just make sure
04:05that I'm deleting it all together.
04:06So I'm gonna go to DB
04:08and I'm gonna make sure that I'm gonna drop data base.
04:13All right, so I've just dropped MongoDB. Beautiful.
04:16Now that I have it dropped, let's go back into our,
04:18our editor and let's continue.
04:20So let's go ahead and do a few bulk operations now
04:23that we know that there's absolutely nothing there.
04:25And I'm gonna go ahead and I'm gonna insert
04:28and lemme just create a template.
04:30We're gonna put users in here.
04:31So, uh, one is gonna be Ben
04:34and his age is gonna be, let's say 33.
04:37His height is gonna be 180 1.
04:41We're working in centimeters and not in inches.
04:44And his charm factor from one to 10 is let's say five.
04:47Um, kind of charming but kind of not really.
04:49Just depends who you ask.
04:52So let's go ahead and just add your, a couple of people.
04:54So I'm just gonna go ahead here
04:55and just paste this a few times.
04:57Or you know what? Let me just paste my pre-created, uh, list
05:01of names of people so we don't have to do this,
05:03uh, manually filling them up.
05:04Okay, so I just filled out here a list of of people
05:08and I want to go ahead
05:09and just inject them into our database to do that.
05:13What I'm gonna do next is I'm just gonna call our bulk
05:17l our bulk object here, bulk block.
05:21Why am I doing that? Why am I doing that? There we go. Bulk.
05:25And I'm gonna click onto execute.
05:27Now I wanna talk about one thing
05:28that we haven't really talked about until now,
05:31which is probably a good time to talk about it.
05:34No, JS in general is not a language where awaits
05:38for something to happen.
05:40It just doesn't, the whole core of no JS is the idea
05:43of IO input output.
05:46So we're basically sending something through the database
05:48and the application is gonna continue working.
05:51So if I send here something
05:52and something is happening below here
05:54that something is gonna happen before this
05:56Actually actually happens in most probability.
05:58So these are callbacks.
06:00And within these callbacks you really wanna almost do
06:02everything within callbacks.
06:04So in this case, we're waiting for this, we're not waiting.
06:07Everything is continuing on as normal
06:09and then we're gonna go ahead and execute something.
06:11Now I wanna show you why this is
06:13important to understand this.
06:15If I do your console log
06:17and let's say I'm gonna say good stuff,
06:20that means it happened.
06:21It's all completed.
06:22Everything has been operated the way we wanted it to be.
06:25Now I'm gonna go ahead in line 15
06:27and what I'm gonna do, I'm gonna call my database
06:29and I'm gonna close it, literally closing the database
06:33on line 15 and you will think that, okay, great.
06:35So we're gonna add everything in
06:37and then close our database.
06:38But notice what's actually really gonna happen in reality.
06:42In reality, if I run my, my my, let me just go ahead here.
06:46I'm gonna NPM oh node
06:50and our file is indexed h js, we don't have to type js.
06:53So note index and we're gonna rent, first of all,
06:56we have your little area here.
06:57So, uh, bulk is not defined.
06:59So we probably have your small typo.
07:01Let's make sure that, yeah, 'cause I called it block bulk.
07:04There we go. Let's give it one more shot.
07:09And we have our good stuff.
07:10Now question is, did we get our items
07:12inserted into our database?
07:15Let's check. So we're gonna go into users
07:18and we're gonna do find and here regard our items.
07:21There definitely did get added in.
07:23So this example was not exactly what I intended for it
07:27to happen, but what I'm gonna tell you is this, in general,
07:29generally speaking, this callback was probably super fast
07:33and we didn't close before we actually completed
07:36all of our operations.
07:37But in general, you don't wanna do things
07:40that depend on things afterwards in here.
07:43So this is a no-no, even if it's the right happens
07:45to work this time around where you actually wanted to
07:49to close and to continue your operations within
07:51your callback.
07:53And basically you want to thread things
07:55and you kind of want to treat it almost like a path
07:57where you're doing something if something depends
07:59on something to happen.
08:00So closing it really depends on us first
08:02finishing our execution.
08:04Then we want to continue it within this callback
08:06because that's how we want to do it.
08:08Although technically right now it worked.
08:10But trust me that if you over time you wanna make sure
08:13that you're not closing something
08:16before the operation was completed and be,
08:19and you don't want to assume that just
08:21because it's in the next line that it was completed.
08:23So you really want to put stuff into
08:25these type of callbacks.
08:26So we started that adding things worked
08:28and it worked brilliantly.
08:29Now what I wanna do next is I'm gonna go ahead again
08:31and I wanna uh, um, drop this uh, users, uh, and I'm,
08:35and I'm just gonna use the terminal for that.
08:37So I'm just gonna go ahead and um, I want to drop DB users.
08:42I'm just gonna drop this collection.
08:45Alright, so we dropped the collection
08:46so it should be empty again.
08:48Beautiful. And now that it's empty again, I want to go ahead
08:51and continue showing a few things that are interesting.
08:54So besides adding and
08:56besides inserting things, I wanna show you
08:58how do you find things
08:59and how do you remove things within node js using mongo js.
09:04So I'm gonna click here on bulk
09:07and I'm gonna find something.
09:09But this time around, let's say I want to find anyone
09:11that is under 30 such as David in this case
09:14and I'll remove all of them.
09:15How about I wanna remove anyone that is under,
09:18yeah, anyone under 30.
09:20So in this case it would be David
09:21and Gloria that will be removed from our system.
09:24Now to do that, what I'm gonna do is I'm gonna go ahead
09:26and send in an object set.
09:28What I want to define, which in our case is the age
09:30and just like we did within our terminal,
09:34I'm gonna say the dollar less than
09:36anyone that is less than 30.
09:38Those are the ones that I want to find
09:39and I'm gonna con concatenate into it
09:42that I wanna remove them.
09:43And by saying remove, I'm gonna remove all of them.
09:46Now what I want, what I'm gonna do now,
09:48I'm just gonna save this and I'm gonna go ahead
09:50and run this just one time
09:52and if I run it, we're gonna see good stuff,
09:54everything worked accordingly
09:56and I'm just gonna find to see what comes back
09:58and you'll see that Gloria and David have been
10:00deleted from our list.
10:02Beautiful. So let's go ahead and note.
10:04So drop them and start this over one more time.
10:09And in our terminal, let's go ahead.
10:11So besides removing an item, I wanna show you
10:13how do you approach an item specifically?
10:16So let's go ahead and in my bulk operations, um, bulk
10:22and I'm just gonna find someone.
10:24So let's say I want to find Ben because it's my birthday
10:28and I need to change my age.
10:31Now I don't have to update all in this case I'm updating one
10:34which basically says that I only want one thing to update.
10:37If there's more than one item in the fine,
10:39then only the first one among them will get updated.
10:43And in this case, I don't wanna change everything about Ben
10:45because if I go ahead here and let's say I set a new item
10:49and I say name from now is Ben.
10:51Let's say like it was already before.
10:54And if I go ahead here, I save this and I go
10:56and I run it just one more time,
10:57notice what's gonna happen this time around by doing this.
11:01If I go ahead and find it, you'll see
11:02that now I change everything inside of my Ben object,
11:06but that's not really what I wanted.
11:08What I wanted was to only update the ben with something new.
11:12To do that what you're gonna do is instead
11:13of approaching something and just updating it,
11:16the whole thing you could set with the parameter dollar set
11:20and then send a list of the things that you want
11:22to update within it.
11:23So in this case I wanna change Ben's age to be 34
11:27and if I do this instead and let me go ahead and also again
11:29and get rid of everything that was there,
11:31clear everything out and restart our application
11:36and give a peek to see what got back.
11:38You'll see that Ben's age will be updated from 33
11:41to 34 instead of just removing it.
11:44I wanna continue to another thing and notice our object id.
11:47How about if I wanna approach something very specifically
11:50and I have its object id,
11:52What you wanna do in that situation.
11:54And I'm gonna go ahead here
11:55and just comment out this BA bulk operation
11:58because we know it exists already.
12:02So let's go ahead and do just one more thing
12:04and I want to show you how to,
12:05besides doing these bulk operations,
12:07and I'm sure you're gonna dig more into the Mongo GS
12:10documentation that's provided
12:12with the appendixes of this chapter.
12:14But I wanna show you also just singularity,
12:17how do you do one thing and I want
12:18to in the same time show you how do you work
12:19with the object id.
12:21So just like we saw,
12:22just if we take a small quick peek in our turn terminal,
12:26we have here this object ID for example of Ben.
12:29And what I really wanna do, I'm gonna copy this
12:30and what I really wanna do is I wanna delete Ben.
12:33So I'm gonna go ahead, which is so sad
12:35'cause I don't really want to delete myself.
12:37But let's say that I do now in, I'm gonna go to my DB
12:41to users and I'm gonna call to remove.
12:43The first operator that I want to do is I'm gonna set the ID
12:46underscore ID
12:48and tell it what I wanna remove, which is that object id.
12:51Now object ID is a function,
12:52but this function does not really exist in the
12:54global space here.
12:56So I'm gonna go ahead and just send it inside
12:59'cause it's inside of our Mongo JS package.
13:02Alright, so with that said, now that I've told the operator
13:06what I want to delete, I'm also gonna tell it
13:08that I only want to delete one thing
13:10that is my second parameter and my third parameter
13:13and this, that will just confirm
13:14that only one thing is being removed.
13:16My third parameter is my callback
13:18and my callback expects to have a error
13:20as the first parameter and a result as the second parameter.
13:24And I'm gonna create here again with our arrow
13:28arrow functions, which are only available from
13:30JavaScript six and onwards.
13:31And if you're running something without JavaScript six,
13:34then just make sure that you're gonna put in a regular
13:36callback and not a arrow callback.
13:39And I'm gonna go ahead here and just call the console log
13:42and I'm gonna say here, Ben was removed.
13:46And last but not least, I'm gonna make sure
13:48that I close my database.
13:49'cause in this case I'm completely done with my operations.
13:52Now in general, you might be thinking when should you close
13:55the database when you're completely done with it.
13:58Now if you're, you have a website
13:59and the user might need something later down the line,
14:03you're probably better off still closing down your database.
14:06But if there's a communication going back and forth and back
14:09and forth and it's continuous,
14:10then you might be from a performance perspective,
14:13better off just leaving the connection
14:15between the user and your database.
14:16So it really depends on the situation
14:18and how often does data come back
14:20and forth between the user and the database.
14:23With that said, let's go ahead and test this out
14:25and I'm gonna go into terminal again
14:27and run my application one more time.
14:30And first of all, I'm getting a small error here, so be
14:32that's because D DB doesn't exist probably.
14:35So let's go ahead and see if that's the error here.
14:38So DB is good, looks to me, good, looks to me good.
14:43DB db, let's take a deeper look into this error message
14:48to see if there's anything more explicit.
14:50Cannot read Property DB of undefined.
14:54And this is happening in line 19.
14:58So let's see what's happening in our line 19. In line 19.
15:02Oh I, I put here a dot instead of a semicolon.
15:05So there we go. 'cause it was looking for the DB inside
15:07of our log, which that obviously does not exist.
15:10So let's go ahead and let's give it one more shot
15:13and I'm just gonna clear the screen
15:14so we don't have such a messy destination.
15:17So Ben was removed, our database has been disconnected.
15:20If we go back and check another find, we should now find
15:23that Ben is not part of the items.
15:25Now Ben was removed and only Bill Ann and Sharon exists.
15:29So there you go. That is really the basics of working
15:32with MongoDB and working with MongoDB inside of node js.
15:36I hope you had a blast.
15:39Congratulate yourself for knowing another technology.
15:43Now in the next section,
15:44we're gonna go a completely different path
15:47as we connect all the dots of all the technologies
15:50that we've explored so far
15:51and learn more about them as we explore a few more things.
15:55But the next section is really gonna be that glue
15:58that binds all of the learning
16:00that we've done throughout the last few hours.
16:02So I'll see you in the last section.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!