Mongoose 101
Mongoose is a library that makes MongoDB easier to use. It does two things:
- It gives structure to MongoDB Collections
- It gives you helpful methods to use
In this article, you’ll learn how to use Mongoose on a basic level.
Prerequisites
I assume you have done the following:
- You have installed MongoDB on your computer
- You know how to set up a local MongoDB connection
- You know how to see the data you have in your database
- You know what are “collections” in MongoDB
If you don’t know any of these, please read “How to set up a local MongoDB connection” before you continue.
I also assume you know how to use MongoDB to create a simple CRUD app. If you don’t know how to do this, please read “How to build a CRUD app with Node, Express, and MongoDB” before you continue.
Connecting to a database
First, you need to download Mongoose.
npm install mongoose --save
You can connect to a database with the connect
method. Let’s say we want to connect to a database called street-fighters
. Here’s the code you need:
const mongoose = require('mongoose')
const url = 'mongodb://127.0.0.1:27017/street-fighters'
mongoose.connect(url, { useNewUrlParser: true })
We want to know whether our connection has succeeded or failed. This helps us with debugging.
To check whether the connection has succeeded, we can use the open
event. To check whether the connection failed, we use the error
event.
const db = mongoose.connection
db.once('open', _ => {
console.log('Database connected:', url)
})
db.on('error', err => {
console.error('connection error:', err)
})
Try connecting to the database. You should see a log like this:
Creating a Model
In Mongoose, you need to use models to create, read, update, or delete items from a MongoDB collection.
To create a Model, you need to create a Schema. A Schema lets you** define the structure of an entry** in the collection. This entry is also called a document.
Here’s how you create a schema:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const schema = new Schema({
// ...
})
You can use 10 different kinds of values in a Schema. Most of the time, you’ll use these six:
- String
- Number
- Boolean
- Array
- Date
- ObjectId
Let’s put this into practice.
Say we want to create characters for our Street Fighter database.
In Mongoose, it’s a normal practice to put each model in its own file. So we will create a Character.js
file first. This Character.js
file will be placed in the models
folder.
project/
|- models/
|- Character.js
In Character.js
, we create a characterSchema
.
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const characterSchema = new Schema({
// ...
})
Let’s say we want to save two things into the database:
- Name of the character
- Name of their ultimate move
Both can be represented with Strings.
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const characterSchema = new Schema({
name: String,
ultimate: String
})
Once we’ve created characterSchema
, we can use mongoose’s model
method to create the model.
module.exports = mongoose.model('Character', characterSchema)
Creating a character
Let’s say you have a file called index.js
. This is where we’ll perform Mongoose operations for this tutorial.
project/
|- index.js
|- models/
|- Character.js
First, you need to load the Character model. You can do this with require
.
const Character = require('./models/Character')
Let’s say you want to create a character called Ryu. Ryu has an ultimate move called “Shinku Hadoken”.
To create Ryu, you use the new
, followed by your model. In this case, it’s new Character
.
const ryu = new Character ({
name: 'Ryu',
ultimate: 'Shinku Hadoken'
})
new Character
creates the character in memory. It has not been saved to the database yet. To save to the database, you can run the save
method.
ryu.save(function (error, document) {
if (error) console.error(error)
console.log(document)
})
If you run the code above, you should see this in the console.
Promises and Async/await
Mongoose supports promises. It lets you write nicer code like this:
// This does the same thing as above
function saveCharacter (character) {
const c = new Character(character)
return c.save()
}
saveCharacter({
name: 'Ryu',
ultimate: 'Shinku Hadoken'
})
.then(doc => { console.log(doc) })
.catch(error => { console.error(error) })
You can also use the await
keyword if you have an asynchronous function.
If the Promise or Async/Await code looks foreign to you, I recommend reading “JavaScript async and await” before continuing with this tutorial.
async function runCode() {
const ryu = new Character({
name: 'Ryu',
ultimate: 'Shinku Hadoken'
})
const doc = await ryu.save()
console.log(doc)
}
runCode()
.catch(error => { console.error(error) })
Note: I’ll use the async/await format for the rest of the tutorial.
Uniqueness
Mongoose adds a new character to the database each you use new Character
and save
. If you run the code(s) above three times, you’d expect to see three Ryus in the database.
We don’t want to have three Ryus in the database. We want to have ONE Ryu only. To do this, we can use the unique option.
const characterSchema = new Schema({
name: { type: String, unique: true },
ultimate: String
})
The unique
option creates a unique index. It ensures we cannot have two documents with the same value (for name
in this case).
For unique
to work properly, you need to clear the Characters collection. To clear the Characters collection, you can use this:
await Character.deleteMany({})
Try to add two Ryus into the database now. You’ll get an E11000 duplicate key error
. You won’t be able to save the second Ryu.
Let’s add another character into the database before we continue the rest of the tutorial.
const ken = new Character({
name: 'Ken',
ultimate: 'Guren Enjinkyaku'
})
await ken.save()
Retrieving a character
Mongoose gives you two methods to find stuff from MongoDB.
findOne
: Gets one document.find
: Gets an array of documents
findOne
findOne
returns the first document it finds. You can specify any property to search for. Let’s search for Ryu
:
const ryu = await Character.findOne({ name: 'Ryu' })
console.log(ryu)
find
find
returns an array of documents. If you specify a property to search for, it’ll return documents that match your query.
const chars = await Character.find({ name: 'Ryu' })
console.log(chars)
If you did not specify any properties to search for, it’ll return an array that contains all documents in the collection.
const chars = await Character.find()
console.log(chars)
Updating a Character
Let’s say Ryu has three special moves:
- Hadoken
- Shoryuken
- Tatsumaki Senpukyaku
We want to add these special moves into the database. First, we need to update our CharacterSchema
.
const characterSchema = new Schema({
name: { type: String, unique: true },
specials: Array,
ultimate: String
})
Then, we use one of these two ways to update a character:
- Use
findOne
, then usesave
- Use
findOneAndUpdate
findOne and save
First, we use findOne
to get Ryu.
const ryu = await Character.findOne({ name: 'Ryu' })
console.log(ryu)
Then, we update Ryu to include his special moves.
const ryu = await Character.findOne({ name: 'Ryu' })
ryu.specials = [
'Hadoken',
'Shoryuken',
'Tatsumaki Senpukyaku'
]
After we modified ryu
, we run save
.
const ryu = await Character.findOne({ name: 'Ryu' })
ryu.specials = [
'Hadoken',
'Shoryuken',
'Tatsumaki Senpukyaku'
]
const doc = await ryu.save()
console.log(doc)
findOneAndUpdate
is the same as MongoDB’s findOneAndModify
method.
Here, you search for Ryu and pass the fields you want to update at the same time.
// Syntax
await findOneAndUpdate(filter, update)
// Usage
const doc = await Character.findOneAndUpdate(
{ name: 'Ryu' },
{
specials: [
'Hadoken',
'Shoryuken',
'Tatsumaki Senpukyaku'
]
})
console.log(doc)
Two major differences.
First, the syntax for findOne
+ save
is easier to read than findOneAndUpdate
.
Second, findOneAndUpdate
does not trigger the save
middleware.
I’ll choose findOne
+ save
over findOneAndUpdate
anytime because of these two differences.
Deleting a character
There are two ways to delete a character:
findOne
+remove
findOneAndDelete
const ryu = await Character.findOne({ name: 'Ryu' })
const deleted = await ryu.remove()
Using findOneAndDelete
const deleted = await Character.findOneAndDelete({ name: 'Ken' })
You learned how to use Mongoose to:
- Connect to a database
- Create, Read, Update, and Delete documents
Thanks for reading. This article was originally posted on my blog. Sign up for my newsletter if you want more articles to help you become a better frontend developer.