Next install Mongoose from the command line using :

    Now say we like fuzzy kittens and want to record every kitten we ever meet in MongoDB. The first thing we need to do is include mongoose in our project and open a connection to the test database on our locally running instance of MongoDB.

    1. // getting-started.js
    2. const mongoose = require('mongoose');
    3. main().catch(err => console.log(err));
    4. async function main() {
    5. await mongoose.connect('mongodb://localhost:27017/test');

    For brevity, let’s assume that all following code is within the main() function.

    1. name: String
    2. });

    So far so good. We’ve got a schema with one property, name, which will be a String. The next step is compiling our schema into a .

    A model is a class with which we construct documents. In this case, each document will be a kitten with properties and behaviors as declared in our schema. Let’s create a kitten document representing the little guy we just met on the sidewalk outside:

    1. const silence = new Kitten({ name: 'Silence' });
    2. console.log(silence.name); // 'Silence'

    Kittens can meow, so let’s take a look at how to add “speak” functionality to our documents:

    1. // NOTE: methods must be added to the schema before compiling it with mongoose.model()
    2. kittySchema.methods.speak = function speak() {
    3. const greeting = this.name
    4. console.log(greeting);
    5. };
    6. const Kitten = mongoose.model('Kitten', kittySchema);

    We have talking kittens! But we still haven’t saved anything to MongoDB. Each document can be saved to the database by calling its save method. The first argument to the callback will be an error if any occurred.

    1. await fluffy.save();
    2. fluffy.speak();

    Say time goes by and we want to display all the kittens we’ve seen. We can access all of the kitten documents through our Kitten .

    1. const kittens = await Kitten.find();

    We just logged all of the kittens in our db to the console. If we want to filter our kittens by name, Mongoose supports MongoDBs rich querying syntax.

    That’s the end of our quick start. We created a schema, added a custom document method, saved and queried kittens in MongoDB using Mongoose. Head over to the , or API docs for more.