Skip to main content

Mongo - Mongoose

Lesson Objectives

  1. Explain what an ODM is
  2. Create a Schema for a collection
  3. Create a model and save it
  4. Find a specific model
  5. Update a model already in the database
  6. Remove a model already in the database
  7. Combine Actions

Explain what an ODM is

ODM stands for Object Document Model. It translates the "documents" being stored in Mongo into fancier JS objects that have more helpful methods and properties.

Create a Schema for a collection

In mongo, you can put whatever you want into your collections. This can be a little dangerous because you might make a mistake in your code. To avoid having the wrong kind of data in your database, Mongoose allows us to create Schemas (or blueprints) for our objects, so that something funny doesn't find its way in.

First install the npm package

npm install mongoose --save
const mongoose = require("mongoose"); //require mongoose package
const Schema = mongoose.Schema; //mongoose has many properties on it. One is a constructor function for Schemas

const articleSchema = new Schema({
title: { type: String, required: true, unique: true }, //can say whether we want properties to be required or unique
author: { type: String, required: true },
body: String,
comments: [{ body: String, commentDate: Date }], // can have arrays of objects with specific properties
publishDate: { type: Date, default: Date.now }, // can set defaults for properties
hidden: Boolean,
meta: {
// can have properties that are objects
votes: Number,
favs: Number,
},
});

//Creating an Article class -- will be stored in 'articles' collection. Mongo does this for you automatically
const Article = mongoose.model("Article", articleSchema);

module.exports = Article;

Here are the most common types of properties you can have

  1. String
  2. Number
  3. Date
  4. Boolean
  5. Mixed
  6. ObjectId
  7. Array

Create a model and save it

Now that we have an Article class, we should import it in another file and use it to create a new Article in our DB. Remember, all the Article class does is set up the blueprint that all article objects must follow. It doesn't create anything in the DB.

const mongoose = require("mongoose");
const db = mongoose.connection;
const Article = require("./article.js");

//connect to mongo
mongoose.connect("mongodb://localhost:27017/example");

//if the connection fails
db.on("error", () => {
console.log("error");
});

db.once("open", async () => {
//we're connected!
//save article to the database
try {
const newArticle = await Article.create(
{
title: "Awesome Title",
author: "Matt",
});
console.log(newArticle);
mongoose.connection.close(); //close the connection so that the program will end
} catch (error) {
console.log(error);
};
});

Find a specific model

The Article class itself has functions that you can call. Note this is not a specific instance of an article, but rather the class.

Mongoose's find method is pretty similar Mongo's.

try {
const articles = await Article.find({ author: "Matt" });
console.log(articles); // an array of articles
} catch (error) {
console.log(error);
};

Update a model already in the database

Mongoose's update method is pretty similar Mongo's, except you will need to print out what has been updated.

try {
const updateArticle = await Article.update(
{ author: "Matt" },
{ $set: { author: "Matthew" } },
{ multi: true });
console.log(updateArticle); //shows you the updated article i.e. update successful
} catch (error) {
console.log(error); //else error will be shown
};

Remove a model already in the database

Mongoose's remove method is pretty similar Mongo's, except you will need to print out what has been removed.

try {
const removeArticle = await Article.remove({ author: "Matt" });
console.log(removeArticle); //shows you the removed article i.e. removal successful
} catch (error) {
console.log(error);
};

Combine Actions

Multiple actions can be done one after another.

try {
const createArticle = await Article.create(
{
title: "Awesome Title",
author: "Matt",
});
console.log(createArticle);

const removeArticle = await Article.remove({ author: "Matt" });
console.log(removeArticle); //shows removed article

} catch (error) {
console.log(error);
};