Transcripts
1. Class Introduction: Welcome back to Module
six of the ExpressJcurse, credit operations with Mongoose. This is a continuation class of the Express JS course series. My name is Shawn aguanhi, you are instructor for
this exciting journey into the world of Mongo
Dew and Mongoose. Having built numerous
data driven applications, I can tell you that
mastering Mongo Dew is an essential skill for
modern Bend developers, and mangos makes it incredibly
powerful and intuitive. In this module, we are diving deep into
Mongo DB and mangos. Here's what you will learn how to connect your NurJs app to MongoDB designing efficient and flexible
data schemas with mangos. And then creating,
reading, updating, and deleting data
using mangos models, mastering advanced queries,
including operators, logical conditions, and
regular expressions. After that, you'll
learn implementing features like pagination
and counting documents. And finally, you will explore the best practices for managing and upgrading
your database. This class is perfect
for developers who want to integrate Mongo DB into
their no JS applications. If you have completed
the earlier modules on restful ABIs and Express Js, we are all set to begin. No prior experience with
MongoDB is required. We will start from
the basics and gradually advance to
more complex topics. By the end of this module, you will have the
skills to build robust data driven applications. Whether you are creating a small personal project or
large scale production app. MongoDB and Mongoose
will give you the flexibility and efficiency
you need to succeed. Finally, in this module, our project is built around a standalone application
called Mongo Demo. This project includes three
focused exercises where you will design mongoo schemas and models to structure
your data effectively, write and execute
crowd operations to manage data dynamically, and implement advanced
techniques like query filtering, pagination, and
updating documents using industry
standard patterns. These exercises
will help you build confidence in working with
Mongo Deb and mangos, preparing you to handle complex data operations in
real world applications. I can't wait to help you master
Mongo Di Bi and mongoose. Let's dive in and get started. See you in the first lecture.
2. Getting Started with MongoDB: Alright, so back to our
Fairwheels application, so far we have
stored the list of companies in an array in memory. That's not how we build real world applications because
when the server restarts, we're going to lose all
the data in memory. So that's why we need to
store our data in a database. Now, as I told you before, when building applications
with Node and Express, you have a large
number of options in terms of the database
you want to use. In this course, we
are going to use Mongo DB because that's a very popular database
management system, and it's quite often used in applications built
with Node and Express. So if we have never worked with Mongo DB before, don't worry. You're going to
learn about it bit by bit or the next few sections. Now, just to set the
right expectation, Mongo be really requires
its own course. So you're not going
to be a Mongo Be expert by the end of
watching this course, but you're going to learn
enough to get the job done. Now, if we have never worked
with Mongo DB before, Mongo DB is basically
what we call a document or no SQL database. It's different from traditional
relational databases like SQL server or
MySQL and so on. So in Mongo B, we don't
have the concept of tables, schemas, views, records,
columns. It's different. So unlike relational databases, where you have designed your
database ahead of time, in Mongo DB, there is no such a thing as
schema or design. Simply store your JCN
objects in Mongo DB. So here we have an
array of companies. We can simply store all the
objects in this array and a collection in Mongo
DB, as simple as that. This also means when
quering our data, we get JCN objects
out of Mongo DB, and we can simply return those objects back
to the client. So there is no transformation. That's enough introduction
about Mongo DB. Next, I'm going to show you how to install
it on your machine.
3. Installing MongoDB for Node.js: In this lecture,
I'm going to show you how to install
Mongo DV on Windows. So open up your browser and
head over to mongodv.com. On this page, on the top left, click on product, and then here, select the option
Community Addition. This is the Mongo DV server
that we run on this machine. Scroll down, check the version, and make sure
Windows is selected. Now download this MSI.
So let's save this. All right. And now let's run it. Click on install anyway. So this gives us a
very simple installer. Let's go ahead. Next, accept
the license agreement. Next, and do a
complete installation. Again, next, now on this page, there is a checkbox here. Install MongoiVKmpas. This is the client
application data we use to connect to
our MongoDB server. We look at our databases. Next, install All right, Mongo DB is installed. And our Mongo DB compass
is also launched, we'll talk about it later. So now let's open
up File Explorer and go to Program Files, and then Mongo DB. Next server. Now, the version
I'm running is 7.0. Chances are, in the future, when you're watching this, the
version will be different. So select that folder and then Ben and then finally
Mongo D. There is Mongo Damon, which is a service that
runs in the background. And that's basically
our Mongo DB server. Now, what I want you to do
is select this path here. Now in the search bar, search for advanced system settings. On this page, we need to go to environment
variables here. And then from this list
of system variables, select Path, click
Edit, and then new. And here we pace the path
that we copied earlier. This is the path
to the directory that contains our
Mongo DV server. Okay? Now on this page,
also select Okay. Jan. Now open up
PowerShell and run Mongo D. If you don't see this output and get an error like Mongo
D is not recognized, you need to restart Power Shell. So close all the PowerShell
windows that are currently open on your
machine and then open it. So when you run Mongo D, you should see an
output like this. By default, you are
going to get an error. So here, look, we
get this exception, non existent path
data directory, C, column backslash data
backslash TV not found. So by default, Mongo DV stores
your data in this folder. So let's create this folder. MKDIR, C colon backslash
data, backslash TV. Okay. Now let's run
Mongo E one more time. This time we don't
get that exception. And the last message is waiting for connections
on port 27017. So this verifies that Mongo
DV server is running. Now we can go to
Mongo DV Compass. So here's the page
to get started. That is connect to host. We need to specify the Mongo DV server we
want to connect to. So leave the default
values as they are. So the host name is local
host and port is 27017. Now, let's connect. Beautiful. We are successfully connected to our
Mongo DV server. So here by default, we
have three databases, Local, Armin and Config. These are for MongaTV
to do its job. We are not going to work
with these databases.
4. Connecting Node.js to MongoDB: Alright. Now let's create a
new project for this section. So I'm going to create a new
folder called Mongo Demo. Let's go in this folder and
run NVM in it with a US flag. Beautiful. Now we need to install a knot package
called Mongoose. Mongoose gives us a simple EPI to work with a
Mongo DB database. Okay, so you can see at the
time of recording this video, I'm using Mongos
version 7.5 0.0. So if you want to
make sure you have the same experience as what I'm going to show
you in this video, I highly encourage you to
install the exact same version. Alright, let's add a new
file here, index dot JS. The first thing we need to do
is to connect to Mongo Deb. So we'll load this
mangos module. And store it in the
constant pongos. Now, this object has a
method called connect. We use this to
connect to Mongo DB. Now here we pass a connection
string that is Mongo DB, Allan 127.0 0.0 0.1. Column 27017. This references the Mongo DV that we installed
on this machine. When you want to deploy your application to a
production environment, you are going to
have a different connection string
for the production. Earlier in this
section about Express, I told you how to manage various configuration settings for different environments. In this video, we are not dealing with that
level of complexity. So I've hard coded a
connection string here. But in real application, your connection string should come from a configuration file. So here's our Mongo DB server. Now, after that, we add
the name of our database. In this case, I'm going to use a simple
playground database. Now we have not created this database,
and it doesn't matter. The first time we write
something to this database, Mongo E B will automatically
create this database for us. Okay, so this is how we connect
to a Mongo I B database. Now, this connect method
returns a promise. So we can call then when
this promise is fulfilled. That means we have connected
to a Mongo Eb database. So here we can do a
simple console dot log connected to Mongo I B. And by the way, here I'm using Tensole dot
log for simplicity. As I told you in the
section about Express, in a real application, it's better to use the debug
module because with that, you have more control
over how much of these debugging
messages you want to see. But in this section, we don't want to get distracted
with too much complexity. We just want to
focus on Mongo DB. So this is for scenario where we successfully connect
to a Mongo IB database. But what if something
goes wrong? We want to catch that error. Here, we get an error object and then display
it on the console. So console dot error. Connection to MangiIBFail. And then we add
the error object. Beautiful. Now, let's
run this application. So back in the terminal, North moon index dot JS. So we can see we are successfully
connected to Mongerib.
5. Designing Data Schemas with Mongoose: So we have connected to
our Mongo DB database. Now the next thing we need
to do is to create a schema. We use a schema to define the
shape of documents within a collection in Mongo DB.
What do I mean by that? Well, let's go back to
our Mongo DB compass. I've created this
database here, ground. And in this database, we have this collection called courses. A collection in Mongo DB is like a table in a
relational database. Now in this collection
Curses collection, we have three documents. A document in Mongo IB is kind of similar to a row in
a relational database. So in relational databases, we have tables and rows. In Mongo DB, we have
collections and documents. Now let's take a look
at this collection. So here's an example
of the document. Each document is a container
of key value pairs. So here we have underline ID, which is a unique identifier. For each document, we have tags, which is an array
of key value pairs. We have name, author, is published, date, and version. Now, don't worry about
how I created this. You are going to learn that
over the next few lectures. Now in Mongoose, we have
this concept called schema. This is just specific
to mongoose. It's not a part of Mongo DB. We use a schema in
mongoose to define the shape of documents in
a Mongo DB collection. So we use that to define what are the properties we
have in this document. Now let me show you how
to create a schema. So back in VS code, let's define a constant, call it course schema. This schema defines
the shape of course documents in our
Mongo DB database. So we set this to a new
Mongoose schema class. Here, when creating an instance of this class, we
pass an object. And in this object, we specify the key value pairs that we should have
in course documents. So you want each course
to have a name property, and the type of this
property should be a string. Similarly, each course should have an author of type string. I want our courses to have X. And here, I want to have
an array of strings. Not technically when
this is stored, each object in this array
will be a key value pair. The key will be the index and the value will be that string. Now also I want
each course to have a date property of type date. Now we can also give
this a default value, so we can change this
from date to an object. This object is a type
property that we set to date, and it also has a
property called default, and we set this to date dot now. With this, we don't
have to specify a date when creating
a course object. Date that now will be used as a default value
for this property. And finally, I want
each course to have a property
called I published, which would be a Boolean. So here's the list of types we can use when
creating a schema. We have string,
number, date, buffer, which we use for storing
binary data, boolean, object ID, which is used for assigning unique
identifiers and array. Next, I'm going to show
you how to create and save a document based
on the course schema.
6. Creating and Using Mongoose Models: So here's our course
schema that defines the shape of course documents
in a Mongo De database. Now, we need to compile
this into a model. What is a model? Well,
earlier in the course, I talked about the concept
of classes and objects. So as an example, I told you that we can have a
class called human, we can have an object like Shen. So an object is an
instance of a class. A class is just a blueprint, but an object is an
instant of that blueprint. Now in this application, we want to have a
class called course. And then we should
be able to create instances of that class,
like a node course. And then we can save that
node course to our database. So to create a
class like course, we need to compile this
schema into a model. So this is how we do this. This mongoose object that
we have has a method called model that
takes two arguments. The first argument
is the singular name of the collection that
this model is for. So in our Mongo EB database, you want to have a collection
called courses, right? So here's a singular
name course. The second argument
is a schema that defines the shape of
documents in this collection. So that is course schema. Now with this, we get a course
class in our application. So we can set this to a
constant called course. And note that here I'm using
paceal naming convention. So the first layer of
course is uppercase, that means this is a
class. It's not an object. Now we can create an object
based on this class. So let's create a course object. And here, I'm using camel case notation because the first letter
of the first word, in this case, course
is lowercase. So we use Camel case to name our objects and pacelcase
to name our classes. So this course, we set
this to a new course, and in this
constructor function, we pass an object, we initialize our course object. So let's set the
properties of this course. I'm going to set the name
to the Express JS course. Set the author to Shiv in. Set the text to an
array of two strings. So we can have Express
and let's say back in. Now this is an
interesting thing about mango or no SQL
databases in general. You can see that a document in Mongo DB can be a
complex object. So here, this tag property
is an array of strings. We don't have
something like that in relational databases. In other words, a row in a relational database
has simple attributes. If you want to model this structure in a
relational database, you need three tables
courses, tags, and an intermediary table
called course tags because here we have a many
to many relationship between courses and tags. Mongo IB or no SQL
database in general, we don't have this structure. We don't have to
define these tables. We don't have to script them. We simply create our objects and store them in a database. That's why we call them schema less. They don't have schema. So here's our tax property. Now the other property
we have is date. But earlier, I defined this
to have a default value. So I'm not going
to set this here, and the last property
is published. I'm going to set this too, true. So let's quickly recap. Once we have a schema, we need to compile
that into a model, which gives us a class. Next, we can create an
object based on that class. And this object maps to a document in a
Mongo DB database. Next, I'm going to show you how to save this document
in our database.
7. Persisting Data with Mongoose: All right. So here's
our course object that maps to a course
document in Mongo DV. Now, let's save this
to our database. So this course object has
a method called save. Now here we are dealing with an asynchronous operation
because it's going to take some time to save this course in the database because we are going to access
the file system. That's why we are dealing with
an asynchronous operation. The result of this operation
will be ready in the future. So this method
returns a promise. We can aviate it
and get the result. This result is the
actual course object that is saved in the database. So when we save this
course in Mongo DB, Mongo DB is going to
assign a unique identifier to this course object with
this course document. Now with this, we can see the IRE that is
assigned by Mongo DB. So let's log it on
the console result. As I told you before,
whenever I use a weight, your code should be
inside an async function. So I'm going to
define a function here, st, create course. We set this to a sync
error function like this and put all this code
inside this function. So we create a course object, save it, and then display
the result on the console. And finally, here we
call create Curse. Save. Now, back in
terminal, in this section, I'm going to run this
application using Node instead of norm
because with no one, every time I make a simple
change in the code, that will result in creating a new document in our
Mongo DB database. So node index dot js. Beautiful. Our course was
saved in the database, and here's the document that is actually stored
in our Mongo DB. Look, Mongo DB assigned
this property underline ID, and it is set to this
unique identifier. Now let's go back to
Mongo DB compass. So let's refresh here. Here's our playground database. We have this courses collection, and in this collection, we
have one document, right? So this is a beauty of Mongo
DB or nose EQUL databases. Unlike relational databases, we didn't have to
create a table. We didn't have to
script that table. Simply created a document and stored it in
our Mongo DB datas. So back in the board, let's modify these values and
create another document. Because in the next lecture, I'm going to show you
how to query documents. So let's change this
to the ReactJS course, and we add two tags, react dot js and front end. Save. Back in the terminal, let's stop this process and
run this application again. Here's our second document. And if you look in MongoiVKmpas, let's refresh the result. Look, we have two documents
in our courses collection. Beautiful. So next, I'm going to show you
how to query documents.
8. Mastering Mongoose Queries: All right now, let
me show you how to drive documents from a
Mong Wo DV database. So here, I'm going to create another function Pas G courses. We said this to Async
error function. And then I'm going to
replace the call to create course with G courses. Now, let's implement
this function. So this course class
that we defined earlier has a bunch of methods
for quering documents. We have find to get
a list of documents. We have find by ID, which is pretty
self explanatory. And we have find one, which
returns a single document. Now we have a few more
fine methods here, but don't worry about them. We use them to find a document and then to remove or update it. We are going to look at
them later in this section. So let's look at fine method. As you can see, this method returns a document query option. Now this document query object
is kind of like a promise. So it has a then method, so we can avid it
and get the result. And with this, we get all
the courses in our database. So let's display
it on the console. Now back in terminal
node index to Js. So look, we get an
array with two objects. Here's our first course, that's the express ts course, and here's the second course. That's the react to Gs course. Beautiful. Now we can
also pass a filter here. So as the first argument to the fine method,
we pass an object, and in this object, we add one or more key value
pairs for filtering. So let's say we want to get
only the courses from Shevn. So we set author to Shevn we
can pass another property. Another filter is
published through. So with this filter, we only get the published courses per sewn, and this is how we
arrive documents. But here we can also
sort our documents. We can set a limit on the number of documents that are returned. We can also select specific
properties in the document. Let's say our course documents
there 50 properties, maybe we don't want to return all these properties
to the client, perhaps you want to
return only their name. So let me show you how to
build a more complex query. Earlier, you saw that this fine method returns
a document query object. Look, document query, right? So here we can customize this query. We can
apply a limit. Let's say, we can
sort the documents. Here we pass an object. And in this object, we add one or more key value
pairs for sorting. So let's say we want to sort these documents by their name. We set name to one. One indicates ascending order. We want to sort these documents
in a descending order, you use minus one. As I told you, you can have multiple key
value pairs here. We also have another
method select, and with this, we can select the properties that we
want to be returned. For example, let's say we
only want to get the name and the tax property of
each course document. So we set name to one
and text to one as well. Now let's run this application, back in terminal node, index Js. So look, now the
course objects that we get have only three properties. Tag the name, we selected
these two properties, but we also get the
underlying ID property that is assigned by
Mongo DB by default. Also, these documents, they are sorted by their name
in descending order. So the react GS
course comes first, even though we created
this course later. So this is how we build queries. In the next lecture,
I'm going to show you how to do more
complex filtering.
9. Mongoose Query Comparison Operators: So in the last lecture, you learned how to use the fine method to
filter documents. Or the next few lectures, I'm going to show you how to
build more complex queries. Now, if you have never
worked with Mongadb before, you will find the syntax
we use to build queries, a little bit
unfamiliar or strange, and I totally understand that because I have
been there before. But in this lecture,
I'm going to show you a technique remember
this syntax, and then you will realize
it's actually very easy. So the topic for this lecture
is comparison operators. So in Mongo DV, we have a bunch of operators
for comparing values. Since mongoose is built on
top of Mongo DV driver, these standard operators
that Mongo Dee understands, they are also
available in mongoose. So here are the
comparison operators that we have in Mongo DB. We have EQ, which
is short for equal, we have NE, which is
short for not equal. We have GT, which is short
for greater than we have GTE, which is short for
greater than or equal to. Similarly, we have LT, which is short for less than. We have LTE, which is short
for less than or equal to. We also have N and NIN, which is short for not N. Now, for the purpose of this lecture, let's imagine our courses
have a price property. I'm going to comment
out this fine method. Let's say we want to get
all the courses that are $10. How do we do this? So we call fine, pass an
object for filtering, set the price to ten, so this returns only the
courses that are $10. Now, what if we want courses
that are more than $10? How can we express this using
JCN objects in JavaScript? Well, you know that
in JavaScript, an object is basically a
collection of key value pairs. So here, our key is price
and our value is ten. With a simple value, we cannot express a concept of more than or
greater than ten. So in order to express the
concept of greater than ten, we need to pass an object. Here, this object is again a container
for key value pairs. Now here, I can use one of
these operators as a key. Let me use greater
than operator here. Do sine will indicate
that this is an operator. GT that is greater than, and we set this value to
ten. So see what I did. I replaced a simple value like ten with an object to
express a concept, the concept of greater than ten. Now we can change this operator to greater than or equal to. If you want courses that are
$10 in the result as well. Let's take this to next level. What if we want to get the
courses that are $10-20? Again, we can use
another operator, so less than or equal to $20. So this is how we can use these comparison operators
to query documents. Now let's look at
another example. Let's imagine we want
to get courses that are $10 or $15 or $20. So I'm going to
commend this out. Let's start from scratch. So we call find, pass an object for filtering,
set the price again. If I use ten, I can only
compare equality to ten. We don't want that. We
want courses that are either $10 or $15 or $20. So we replace this value with an object to
express our query. Now here, we use an
operator that is dollar in. Now, what would we
use for the value? Here, we want to express
a query where courses are either $10 or $15 or $20. So we are dealing with
three values here. What Javascript construct do we use to express
multiple values? We use an array, right? So ten, 15, 20. See what I've done so far. I haven't memorized anything. I just try to logically think, how can we use how
Script constructs to express a concept
to express a query. So these are the
comparison operators. And the next
lecture, we're going to look at the
logical operators.
10. Logical Operations in Mongoose Queries: In this lecture, I'm
going to show you how to use the logical
query operators. So here's our original query. We're getting all the courses
that match this criteria. They are authored by Shevin
and they are published. What if we want to get the
poses that are published by Shevin or the courses
that are published? So we can have courses
that are published, but they are not
authored by Chevan. That's where we
need the operator. So here are the logical
operators we have. We have R and M. See how we
can use these operators. So I'm going to
commend this out. Instead, we're going to call the fine method
without any filters. After that, we
call the R method. Now, here's a question for you. What Java strip construct do we use to store
multiple values? We use an array, right? So here we need
to pass an array, and in this array,
we add two objects. Each object is a filter, just like the filter object that we pass to the fine method. So in this first filter
object, we add author. We set this to Shi in a second, we add this published, and we set that to true. Now with this, we'll
get courses that are authored by Shevin or
courses that are published. The N logical operator
is exactly the same. But instead of using the method, we use the method. And with this, we pass an
array of filter objects. Now this is
technically similar to passing a filter object
to the find method. But sometimes in more
complex queries, you may find a place
for using the N method. Next, we're going to look
at regular expressions.
11. Harnessing Regular Expressions in MongoDB: So back to our original query, in this example, we're getting courses whose author
is exactly the string. Here, if we have a
course with authors such as Shevin or Shevin a Guanhi, those courses will
not be returned. So if you want to
have more control over filtering strings, you need to use a
regular expression. Let me show you how that works. So I'm going to
comment this out. Let's say we want to get courses
whose author starts with Chewn this is how we
write this query. So find as an object,
set the author. Now instead of passing
a string here, we pass your regular expression. So we add a slash, we
add a pattern that we are going to modify in a
second, and another slash. So this is a syntax for representing a
regular expression. Now in regular expressions, we can use this carat character to represent a string that
starts with something. Here, I can add Shen. So this regular expression represents a string
that starts with Shen. So as long as the other
starts with Shen, it doesn't matter what we have. Those courses will be retired. Now, what if we want to look for courses whose author ends
with a given string? Let's say ends with Ragan G. So this is how we
write this query. Fine, as an object, we set the author to
a regular expression to slash pattern. And the pattern we use
here is Rugen hi Dasg. A doll sine in
regular expressions indicates the end of a string. So here we are
looking for courses whose author ends with abonci. Now, this query is
case sensitive. If you want to make
it case insensitive, you append an I at the end. And finally, let's look
at the last example. What if you want
to look for poses whose author contains
the word ship? So shift can be
at the beginning. It can be in the middle, or it can be at the end. So let me show you how
to write this query. So we call fine as an object,
author, regular expression. Here's our pattern. Dot,
star, shift dot star. So that star in a
regular expression means we can have zero
or more characters. We don't care what
those characters are. So with this pattern with
this regular expression, we can have zero
or more characters before or after shift. And once again, if you want to make this case insensitive, we put an I at the end. Of course, you can use more
complex regular expressions. The explanation of JavaScript
regular expressions is beyond the scope
of this course. So if you want to learn more
about regular expressions, just read a tutorial about JavaScript
regular expressions.
12. Implementing Pagination with Mongoose: So in this query,
you are filtering our courses and picking only their name and
tax properties. So if you run this application, this is what we get an
array of two courses. And each course has
these three properties. Sometimes we just want
to get the number of documents instead of
the actual documents. So if that's the case, we don't need to
use select method. Instead, we call count, and this returns the count of documents that match
this criteria. So back in terminal, let's
run this application again. Look, we have two documents
that match our filter.
13. Mongoose Update Patterns: Query First Approach: So earlier you learned
about this limit method. A method that goes
hand in hand with the limit method
is a skip method. And we use this to
implement pagination. Let me show you how this works. So let me define a constant
called page number. This can be one, two,
three, whatever. So let's set this to two. We have another constant
called page size. Yeah. So I've hard
coded these numbers. That's purely for simplicity. But in a real world application, we pass these values as query string parameters
to restful APIs. So you might have an API to
get the list of courses. It's endpoint can get query
string parameters like this. So page number, we set this to two and page size,
we set this to ten. This is how it works
in the real world. For now, we don't
have to worry about this. So let's delete this. In order to implement
pagination, we need to skip all the
documents in the previous page. So here's the formula. Page number minus
one times page size. So here, I'm assuming page
number starts from one. So more accurately, this is
page number, not page index. Okay? And then we change
limit to page size. With this, we can get the
documents in a given page.
14. Mongoose Update Patterns: Update First Approach: So you learned a lot
about queering documents. In this lecture, I'm
going to show you how to update documents
in Mongo DB database. So let's create a new function. So last update course. We set this to an error function and it should take an ID. So as ID, fed R goes
to a coord block. This is the ID of the course. We're going to update
it, and then here, we're going to replace
this with update course. Now there are basically two ways to update a
document in MongaiV. One approach is what I
call where you first. So you find a document
using Fine by ID, then we modify its properties. And then finally,
call the save method. This is probably the approach that you have used
in other frameworks. Now the other approach is
what I call update first. So instead of retrieving
a document first, we go in the database
and update directly. Now we can often get the
updated document as well. So in this lecture, I'm going to show you
the first approach, and we'll look at the other
approach over the next video. So let's delete all
these comments. Here we want to get the
course with a given ID. So course dot Fine By ID, we pass this ID here. Now, this returns a promise, so we away it, get the
result and store it here. Now, chances are there is
no course with a given ID, so we need to check for that. If we don't have a course, we are going to return immediately. Otherwise, we are going to upgrade the properties
of this course. So we can set course
dot is published to true and also author to another author. There is another approach. Instead of setting
multiple properties, we call the set method. So course dot set. Here we pass an object with key value pairs to be updated. So we can set is published to true and author to
another author. So basically, these two
approaches are identical. Which one you choose is purely
your personal preference. Now in this demo, I'm going
to use the first approach, and finally, we call
the save method. This is the same method that we used earlier, create
a new course. So it returns a promise. We can awate it, get the result, and display it on the console. So console dot log result. Now I'm going to
go back encompass and get a valid course ID. All right. So here in
our courses collection, I'm going to grab this
course ID and paste it here. Now, back in terminal, let's run this program. Here's the course
that we updated. Look, author is set
to another author. In the next lecture, I'm going
to show you how to update a document directly in the database without
retrieving it first.
15. Counting Documents with Mongoose: I in the last lecture, you learned about the
query first approach to update a document. This approach is useful if
you receive an input from the client and you want to make sure that the update
is a valid operation. For example, here we
have a business rule. So if the course is published, maybe we should not be
allowed to change its author. To implement this business rule, we need to retrieve
the course first, and then we need to write
some logic like this. So if course is published,
we want to return. We don't want to
update this course. So that's when we use the
query first approach. But sometimes, you know
what you are doing, you are not receiving
input from the client. You just want to
upgrade document or perhaps multiple documents
directly in the database. And that's what I'm going to
show you in this lecture. So instead of using
the fine by ID method, we use the update many
or update one method. Now, the first argument here is a query or a filter object. So we can get the
course with this ID, or we can pass
something more generic. We can get all the courses
that are not published. So with this, we can update
multiple documents in one go. Now in this demo, we want to update a course with
a particular ID. I'm going to change
this to underline ID and set this to ID argument. Now the second argument to the update one method
is the update object. Now here we need to use one or more of the Mongo DB
update operators. So if you search for Mongo
DB update operators, On this page, you
can find the list of all the supported operators. So we have current date to set the value of a field
to the current date. We have ink or increment.
This is very powerful. With this, we can
increment the value of a field by the specified amount. Imagine you want to build an
application like Facebook. So when the user likes a post, you want to increment
the number of likes. This operator, you can increment the number of s directly
in the database. You don't have to
retry the post first, then increment the number
of s. You can also pass a negative value to
decremente the value of a field. We have men which is useful
if you want to update a field if the specified value is less than the
existing field value. We have another similar
operator, and with this, we can update a field if the specified value is greater than the
existing field value. We have L or multiply, which is kind of
similar to increment. But with this, we can multiply the value of a field
by the specified amount. We have set, which I'm going
to show you in this lecture, and with this, we can
set the value of field. And similar to
this, we have set, which we can use to remove the specified field
from a document. So back here in
our update object, I'm going to use
the set operator. We set this to an object, and in this object, we add
one or more key value pairs. So let's say we want to
upgrade the auor property, set it to Shevin, and we want to set is
published to falls. So with this update one method, we can update a
document directly in the database without
retrieving it first. Now, what we get here is the result of the
update operation, not a course object. So let's rename this to result. Now we don't have to check for
the existence of a course. We don't have to update
the properties here, and we don't have to save it explicitly. Okay, very simple. So let's go back in the terminal and run our application again. So you can see here in
the results object, we have modified one document. And here is this document
in our Mongo DV database. So author is set
to Shiv in and is published is set to
false. Beautiful. Now, sometimes you want to get the document
that was updated. If that's the case, instead of the
update one method, you need to use fine
by ID and update. So here, as a first argument, we need to pass an ID
instead of a query object. And similarly, as
the second argument, we pass our update object. Now, what we get here
is a course object. So I'm going to
change the author to Shevin and is published to True. Let's run this program
and see what happens. So node, index or Js. All right, here's the course
document that we updated. However, look, the
author is still shivn and is published is false. So what we get here is the original document that is the document before
the update operation. If you want to get
the updated document, you need to pass an option. We need to pass another
argument to this method. Here I pass an object and set
the new property to true. And with this, we'll get
the updated document, save. Now, back in the terminal, let's run the application again. Okay, look, Author issuing
and is published is true. So with this method,
we will send one command Mongo Dev to
update document and return it. Next, I'm going to show you
how to remove a document.
16. Removing Documents in Mongoose: In this lecture, I'm going to show you how to
remove a document. So to save time,
I'm going to get the port for the update
course function, duplicate it, and then rename
this to remove course. And finally, replace
this with remove purse. All right. Now let's
implement this function. So to delete a document,
we call course. Here we have this
method, delete one. This method takes a
filter or a query object, so we can pass an
object like this. And with this query object, we can find a document
with a given ID. Now, if we send something more
generic like is published, set to false, we might have multiple courses
that are not published. This method, delete one will find the first
one and delete it. Now in this demo, we
don't want to use this. I'm going to revert this
back to this query object. Now similar to the
update one method. This method returns a
promise, so we can away it, get the result,
and store it here, and then log it on the console. Now let's run this program, so no index dot js. Okay, here's our results object and you can see that
we have deleted one document. Now if you want to delete
multiple documents, instead of delete
one, use delete Manu. This method also
returns a result object that shows the number of
documents that were deleted. Now, if you want to get the
document that was deleted, we have another method here. So pose dot fine
by ID and remove. So you pass the ID here. This returns to promise. We await it, get the result and store it
in this course object. So now I'm going to commend
out this first line. And we already
deleted this course. So let's run this program
and see what happens. Node indexed or hs. So we get NO. So if we don't have a
course by the given ID, this method will return NOP