Press "Enter" to skip to content

MERN Stack & GraphQL – #5 MongoDB and Mongoose


right so the next step of course would
be to set up a database for us now you
could of course set it up locally on
your machine so you could go ahead and
install multi TB and then wire it up to
your app directly you could also use
docker for setting up a MongoDB
container on your system as well but I
think what I’ll be doing for this
tutorial though especially because my
operating system doesn’t really support
docker yet I’ll be using a service known
as M lab now you might as well be using
something like Mongo Atlas or as I said
you could even be using a local database
it doesn’t really make any difference
whatsoever your database could be
anywhere on the local machine or
somewhere else overseas and somebody
else’s server it really doesn’t make any
difference at all
so for this tutorial like I said I’ll be
using M lab which is a database as a
service for MongoDB it’s very easy to
set it up you basically need to create
an account with your credentials your
email and a password it’s very very
simple so I would leave that step up to
you but once you do create the account
for yourself you’re gonna be redirected
to a page that looks something like this
for you it’s basically going to be empty
because you won’t have any databases set
up yet I do have a couple from other
projects but what I’m gonna do is I’m
gonna create a new database what I’ll do
is I’ll click on this create new button
this is gonna create a new database for
us so I’m good with Amazon Web Services
let’s select a sandbox option now click
on continue I’m gonna select Us East
because I’m located in Canada but you
could basically select the one that’s
closest to you now clicking on continue
we can call it chat so be the name of
our database continue so everything
looks good it’s all free we don’t have
to pay anything so submit order it’s
gonna take a bit of a second couple of
seconds to create a database it should
be all good to go
so if I click on it now we can go ahead
and create a user you’re actually going
to see a warning that we’re missing a
user the user is actually required to
connect to the database so what I’m
gonna do is I’m gonna click on add user
in fact let me go back to my editor and
here we’re gonna go ahead and add a few
other configurations so I’m gonna create
a database username and this would be
the name for user also let’s say admin
for the database password
to the base password equals and this of
course can be anything but I’m gonna go
ahead and put in the database username
admin I paste in the password and create
this is gonna create the user now once
the user is created we can actually go
ahead and copy the domain of the
database we can also copy the port and
of course the name of the database
itself we could of course connect it to
a shell so if we have a MongoDB client
locally we could also connect it using
that client so it can actually inspect
the database run some commands off of it
but we’re actually gonna be using it for
the application so let me copy the
domain name I’m gonna go ahead and
create a database host let’s put an e
host for that database we’ll have a
database port we need to also copy it
from here and it’s gonna be this second
thing over here and of course the last
one to be the database name and in this
case we call it chat so I’m gonna use
that name and these variables really
don’t belong to this file so I think
what I’ll do is I’m gonna cut them and
paste them to a different file let’s
create a conflict JS file we can paste
those variables in and we can basically
export all of them out of that file we
can now basically go ahead and import
those VARs on demand we know that we
need an airport variable we need node
environment actually we need in prod so
once we have those two we can import
them from config and of course we’re
gonna use the database variables in a
second so what I’m gonna do is I’m
actually gonna switch back to the
terminal let me clear it out what we
need to do is we need to install a
library called Mongoose as I mentioned
before Mongoose is the MongoDB orem
which allows us to work with the data
using models of course there is a native
driver for MongoDB on nodejs but using a
library like Mongoose is basically going
to simplify the way that we work with
our data so we’re gonna go ahead and use
that libraries so let me do a yarn add a
mongoose once mongoose is added we can
basically go ahead and copy these
variables we’re gonna use them so you
create a connection so let me paste them
in over here and this thing could be on
its own line like this so going back to
the documentation let’s get married docs
i’m gonna switch to let’s say schemas
i’m gonna go ahead and try to look for
connect
so there’s quite a few ways to do it and
one of them would be to pass the entire
information so something like the user
and password info as well as the
database URL itself back in here we’re
gonna do an import of Mongoose from a
mongoose so we’re gonna go ahead and set
up a mongoose connection so let’s do
mongoose connect i’m gonna be using
backticks and we’re gonna copy the
string up from the dock so we’re gonna
use that as a reference so let me paste
that in now the first thing is gonna be
the database username so let’s do DB
username next up we have database
password so DB password and we have the
host so this would be DB host
we have a port so let’s put any ports
and let’s stop we have the database name
itself so database name like this and
now the other thing we also might want
to pass is a object with a bunch of
configurations you can go ahead and tell
Mongoose to use new URL parser so we’re
gonna set that option to true now this
function call is going to be a
synchronous so we can either chain is
then on it but what I’m actually gonna
do is I’m gonna create a self invoking
async function so I’m gonna put in a set
of closing brackets at the end I’m going
to take all this code from there and put
it inside the function so this way we
can actually use a weight on this call
now of course this might fail and if it
does we’re gonna get a nasty wording and
the console referring to the unhandled
promise rejection and something like
that so we can go ahead and actually to
a try-catch on it so let’s do that and
if there’s an exception we’re gonna
basically do a console error on it now
I’m not gonna be using Morgan or debug
or anything like that just yet
if we do find a reason to use them we
can always pull them in but for now I’m
gonna keep it simple so now to test the
connection we can go back to the
terminal look into a yarn da and if the
connection was successful you’re gonna
see the URL to our end point but if
something went wrong you might have to
go back and check that your connection
string is correct you may need to also
make sure
that you’re passing the use new URL
parser option to Mongoose and once we’ve
done that we can actually go ahead and
create a models folder so this one is
gonna house all the Mongoose models so
we can create a user model and also
create a not a folder but a file
actually and in the XJS which is
basically going to be an entry point to
that folder so we can basically export
the fault as user from user in this way
we can go ahead and inside of user we
can actually have a an export default of
something so we’re gonna figure it out
in a second but first of all let’s do an
import of Mongoose from Mongoose and so
we’re gonna create a constant let’s do
user schema so we need to do is we need
to new up the schema so let’s call it a
mongoose that’s schema we can pass in an
object the first object is going to be
the definition for our schema once again
this is gonna be pretty much identical
it’s you the type definition so we can
actually pull it up and display it on
the right side we’re gonna have a list
of the same exact fields so things like
user name and create it at in fact let
me just copy everything from here and
I’m gonna put it in over here now as far
as the types and Mongoose the types
could be something like string a number
could also be an object ID which is a
special type but in this case we don’t
have to define an ID the ID is gonna be
created for us implicitly the other
thing we could do is we can actually
provide an object in here this way we
can have a more customized field so for
example we could set the type to string
it’s gonna be the same as setting the
value itself to the string but we can
pass an a configuration object we can
also supply options like let’s say
required we could set it to true we
could also set up an option to trim for
example this is gonna trim the
whitespace from our values we could also
set up some validation rules
exactement length for example the email
must only be of length for example 6 and
in fact you could also pass in an array
you could provide a custom message like
email
must be at least six characters you get
the idea and besides there’s also an
option known as unique now this one
trips up a lot of people actually unique
doesn’t necessarily do what you might
think it does so for instance in the
sequel databases like my sequel or
Postgres if you set a unique constraint
on a field it’s gonna make sure that you
can’t have two records with the same
value for that field so if we do that
for the email it’s gonna ensure that the
email cannot be duplicated now in
Mongoose it’s a little bit different the
enforcement is actually set through a
unique index so this unique property is
actually a shortcut for that so you can
actually go ahead and do something like
user dot insert many and you can insert
an array of multiple user objects with
the same email so because the index for
the email field has not been updated yet
you could still technically insert
multiple users with the same email so
this validation is not really strict or
not really precise so we’re gonna be
using a different mechanism for it just
to be safe and in fact I won’t even use
something like required because there’s
several places where we’re validating or
arguments so what I’m talking about is
we have an implicit argument validation
inside of our schema so for example if
we’re calling a Sun app mutation we
already have a basic validation as far
as the types goes so for instance the
email field has to be a string so it can
be something like an int or it can be a
boolean so it must only be a string and
graphical will also validate that the
email field is also required so it
cannot be something like null for
example so this check for required well
we might as well leave it off because
the validation will be happening at
graph QL level we’re also going to be
doing a bunch of custom validations so
things like minimum length or maximum
length or validating the password field
for example there’s quite a lot of
custom validation that we want to
incorporate into the app in doing all of
it inside of Mongoose is actually quite
cumbersome and Mongoose does have quite
a few limitations so for example the
validation will not happen automatically
when updating a record and you actually
have to pass in the option so you have
to be explicit about validation and we
already saw the unique property
which doesn’t necessarily behave the way
that you would expect it to behave so
we’re gonna keep it simple for now we
might come back to the schema in the
future if we want to add some more
database oriented checks so for example
to check if the username has not been
taken yet so we might actually add some
custom validation afterwards but either
way we’re gonna talk about that
extensively in the validation video or
section so for now we’re gonna keep it
very very simple and in the end what
we’re gonna do is we’re gonna go ahead
and call Mongoose dot model and we can
assign this a user string this is gonna
be the name for the model and the second
argument will be the user schema of
course now the last thing I’ll do is
I’ll pass an East second object to the
user schema so be careful about the
order of the arguments the first one
defines the schema the second one passes
the options as the options that like to
set the timestamps to true this way we
don’t have to define they created that
field ourselves it’s gonna be added by
Mongoose so this one is gonna add
created add as well as updated at fields
implicitly and of course they’re gonna
be updated as the model is being updated
itself and now instead of they created
at field we’re going to define another
one this one of course is going to be
the password we’re gonna store the
password in the database but once again
we’re not going to be exposing it
through the graphical API we’re gonna be
taking it as an argument to this signup
mutation but we’re not gonna be exposing
it to the public it’s only going to be stored behind a server in a database

Please follow and like us: