Introduction
Mongoose is our Object Document Mapper (ODM). An ODM is a tool that sits on top of our database connection that makes it FAR easier to interact with in our full-stack applications.
Initialization
First we need to add it as a dependency to a project that is already connected to a database or create a new one. This walk through will assume you already have a project with a database connection. From your project root run npm i mongoose
. We're now ready to see the difference between communicating with Mongo through their own channels and how it looks with Mongoose.
Example File
Here's what our code should look like:
const mongoose = require("mongoose");
mongoose.connect(
"<db-url>",
{ useNewUrlParser: true }
);
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {
console.log("Connected to the DB!");
});
const Car = mongoose.model(
"Car",
new mongoose.Schema({ make: String, model: String })
);
const modelThree = new Car({ make: "Tesla", model: "Model 3" });
modelThree.save((error, savedModelThree) => {
if (error) return console.error(error);
console.log(savedModelThree.make, savedModelThree.model);
});
What...
Yea... Let's break that down. It's a lot, but it's not so bad.
mongoose.connect(
"<db-url>",
{ useNewUrlParser: true }
);
mongoose.connect()
accepts 2 parameters, the url for the location of your database, and a configuration object. You can read more on the config object from the docs. For now, just know that you need it and it needs to contain that specific property.
The DB
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {
console.log("Connected to the DB!");
});
- So we can use the
mongoose.connection
property effectively ONLY after we have calledmongoose.connect()
. The value of this property will be the actual DB connection. db.on("error", ...)
will give us feedback if there was an error connecting to the DB.db.once("open", ...)
actually opens the DB connection and gives us feedback (via theconsole.log
) the we have successfully connected.
Mongoose Models
const Car = mongoose.model(
"Car",
new mongoose.Schema({ make: String, model: String })
);
So Mongoose provides us with its own model()
method to allow us to create unique Documents that adhere to a strict schema. A DB schema is essentially a map of what kind of data your model should accept. So in our case make
and model
in Car
need to be Strings.
Documents
Now let's take a look at using the model that we just created.
const modelThree = new Car({ make: "Tesla", model: "Model 3" });
modelThree.save((error, savedModelThree) => {
if (error) return console.error(error);
console.log(savedModelThree.make, savedModelThree.model);
});
So first we need to make an instance of the model with specific data. In our case we're making a Tesla Model 3. (if only...) The next line illustrates some functionality that Mongoose gives us that differs from just creating a normal JS object. The .save()
method is one we get specifically from Mongoose. We pass it a callback with an error
param and a second parameter that represents the object that we saved, if it saves successfully.
In this callback we essentially say that if there is an error, print it to the console and break out of the function (because of the return
). After that, we can do anything we want with the returned data. In this case we're logging it but usually we would send it to a template.
Conclusion
Mongoose provides a super helpful abstraction on top of Mongo for us that allows us to interact with our DBs so much more efficiently. Make sure to dig into the docs for a much more in depth look at this software.