Databases-Cheatsheet MITWEBLAB
Databases-Cheatsheet MITWEBLAB
CHEATSHEET
Connecting to MongoDB and using Mongoose, a NodeJS library that allows MongoDB integration
MongoDB
Terminology Schema
Types
Database
String
–
Text
A
database
is
used
to
store
all
collections.
Number
–
An
integer
Date
–
A
single
moment
in
time
Collection
Buffer
–
Binary
data
Stores
a
number
of
documents.
A
collection
should
store
Boolean
–
One
of
{true,
false}
documents
of
the
same
type,
although
this
constraint
is
Mixed
–
"Anything
goes".
If
set
to
mixed,
any
other
not
explicitly
enforced
by
MongoDB.
type
will
be
accepted
ObjectId
–
A
unique
ID,
typically
used
to
identify
Document
documents
Each
record
in
a
collection
is
a
document.
Documents
are
Array –
A
list
of
values
composed
of
key
/
value
pairs.
const
someSchema
=
new
Schema({
ObjectId
names
:
[String],
The
ObjectId
class
is
the
default
primary
key
for
a
items
:
Array,
MongoDB
document
and
is
usually
found
in
the
_id
fi eld
});
in
an
inserted
document.
All
documents
are
You
can
and
should
specify
the
type
of
the
elements
inside
automatically
assigned
a
unique
id
when
added
to
a
an
array,
as
in
this
example.
Names
has
a
specified
type
of
collection.
elements
in
the
array
while
items
does
not.
Mongoose
Terminology Mongoose
Installation
Add
the
Mongoose
package
to
your
project
Schema
A
description
of
the
data
structure.
A
Schema
defi nes
the
fi eld
names
and
their
corresponding
time,
which
helps
$
npm
install
--save
mongoose
with
validation,
defaults,
and
other
options
in
our
models.
Model
Import
Mongoose
A
model
is
the
primary
tool
for
interacting
with
The
Mongoose
package
needs
to
be
included
in
every
MongoDB.
It
is
a
fancy
constructor
for
a
document.
JS
file
it
is
used
in.
Models
are
responsible
for
creating
and
reading
documents
from
the
underlying
MongoDB
database.
const
mongoose
=
require("mongoose");
Validation
Imports
the
package
and
saves
to
the
constant
mongoose
By
default,
MongoDb
does
not
require
the
documents
in
a
collection
to
have
the
same
schema.
In
other
words,
the
documents
do
not
have
to
have
the
same
fi elds
and
data
types.
Validation
allows
you
to
defi ne
the
structure
of
the
Setting
Up
Atlas
documents
in
a
collection.
Atlas
is
an
online
service
that
hosts
Mongo
databases.
Sign
up
at
www.mongodb.com/cloud/atlas.
Create
a
If
a
document
does
not
fi t
the
schema,
the
insertion
will
cluster,
a
user
with
at
least
read
write
permissions,
and
be
rejected. connect
to
your
project.
INTRO
TO
DATABASES
CHEATSHEET
Connecting to MongoDB and using Mongoose, a NodeJS library that allows MongoDB integration
Connect
to
MongoDB Finding
a
Document
Use
your
SRV
from
our
MongoDB
provider,
Atlas,
to
We
will
be
using
queries
to
find
documents
in
a
collection.
connect
with
Mongoose.
const
mongoConnectionURL
=
"mongodb+srv://
USERNAME:[email protected]/test?
retryWrites=true";
const
databaseName
=
"someDatabaseName";
const
options
=
{
useNewUrlParser:
true,
useUnifiedTopology:
true,
Defining
a
Query
dbName:
databaseName,
A
query
describes
how
to
filter
documents
to
specify
};
which
documents
to
return.
mongoose.connect(mongoConnectionURL,
options)
.then(()
=>
console.log("Connected."))
const
emptyQuery
=
{};
.catch((error)
=>
console.log(`Error
connecting
to
MongoDB
${error}`)); An
empty
query,
as
above,
returns
all
documents.
Here
mongoURL
is
set
to
the
SRV
given
for
a
cluster
on
Atlas
const
query
=
{
name:
"Tim",
age:
21
};
This
query
would
return
all
documents
with
the
name
Tim
and
the
age
21.
Creating
a
Schema
const
StudentSchema
=
new
mongoose.Schema({
name
:
String,
age
:
Number,
classes
:
[String],
});
Here
we
have
created
a
schema
with
attributes
name,
age,
Finding
with
a
Query
and
class.
Name
is
a
string.
Age
is
a
number.
And
classes
are
Below
are
two
ways
to
find
using
a
query.
an
array
of
the
specific
type,
String.
Student.find(query)
.then((students)
=>
console.log(`found
${students.length}`));
Creating
a
Model Find
returns
a
Promise
with
all
documents
that
match
the
A
model
is
compiled
from
a
Schema. query.
Here,
our
anonymous
function
takes
the
returned
documents
and
logs
some
information.
module.exports
=
mongoose.model("ModelName",
StudentSchema); Student.findOne(query)
.then((student)
=>
Here
we
created
a
model
based
on
the
schema
we
defined
console.log(`found
${student.name}`));
above.
Remember
that
the
first
argument
specifies
the
name
of
the
collection. Find
one
returns
only
one
document
that
matches
the
query.
INTRO
TO
DATABASES
CHEATSHEET
Connecting to MongoDB and using Mongoose, a NodeJS library that allows MongoDB integration
Finding
Documents
with
a
Certain
Deleting
a
Document
Key-Value
Pair Student.deleteOne(query)
Below
are
two
ways
to
find
a
document
with
a
certain
.then((student)
=>
console.log("Deleted"));
key-value
pair.
This
only
deletes
one
document
that
matches
the
query.
Student.find({
key
:
someValue
})
.then((student)
=>
console.log("Found")); Student.deleteMany(query)
.then((student)
=>
console.log("Deleted
many
documents"));
Student.find({})
.where(key).equals(someValue)
This
only
deletes
one
document
that
matches
the
query.
.then((student)
=>
console.log("Found"));
Inserting
a
Document
const
student
=
new
Student({
Common
Mongo
Errors
name:
"myname",
Make
sure
you've
installed
and
imported
Mongoose.
age:
20,
classes:
["weblab"],
If
connection
issues
to
Atlas,
try:
})
*
checking
the
validity
of
your
Atlas
SRV
student.save()
.then((student)
=>
console.log("Inserted"));
*
restarting
your
server
and
try
again
We
create
a
new
Student
document
and
then
save
it
to
insert
the
document.
Updating
a
Document Helpful
Resources
Student.findOne(query)
https://mongoosejs.com/docs/index.html
.then((student)
=>
{
student.fieldToUpdate
=
newValue;
https://gist.github.com/subfuzion/9236165
student.save()
});
https://www.mongodb.com/collateral/quick-
reference-cards
We
use
find
one
to
ensure
that
we
only
update
one
document.