How to Install and Use Mongoose With Node.js for MongoDB
Tags: Database, Nodejs, Mongodb, NoSQL, Mongoose

Before inserting any document into database, we should first create a schema which explains the structure of the documents to the system. A schema should look like this.

5. Create Schema

const dogSchema = new mongoose.Schema({

name: String,

age: Number,

breed: String

});

Now that we have a schema, we can create a collection. This schema will be the blueprint of the documents into that collection. We will use mongoose.model( ) method in order to create the dogs collection.

6. Create Collection

const Dog = mongoose.model("Dog", dogSchema);

There are some points you should note in the above code line.

Firstly, we passed 2 parameters into the function. First one declares the name of the collection. Mongoose automatically convert the first parameter to lowercased plural form to set the collection name. So, the colllection name is “dogs” in this case.

Second parameter is the schema of the documents that we want to use for our new collection. By passing dogSchema we declare that, every document in dogs collection are type of dogSchema. Things will get more clear when we create a new document just below.

7. Create a new Document

const dog = new Dog({

name: "Rex",

age: 1,

breed: "Golden Retriever"

});

Alright, everything is ready. Only thing left is to save the new dog object into the collection and that is the easiest step.

8. Save the Document

dog.save();

Be careful with this code line. If you call it publicly inside your app.js file, every time you run your file, this line saves another item into the database. It’s a good idea to comment out that line after running it for the first time. You can also use an if statement if you want a permanent solution.

You can always check the situation of the database to decide whether you accomplished these steps successfully. So. let’s do that.

9. Check DB

#go to the command line

#be sure mongoDB is running mongo

#now we are in mongo shell >show dbs

#there must be dogsDB in the list >use dogsDB

# switched to the dogsDB >show collecitons

# we should see dogs collection here >db.dogs.find()

# now we should see the documents in dogs collection, we have one:

# {name: "Rex", age: 1, breed: "Golden Retriever"}

10. insertMany( ) in Mongoose

Dog.insertMany([dog1, dog2, dog3], function(err{});

After that you created the collection, whenever you want to insert more than one item into there, you can call insertMany( ) function. Note that dog1, dog2, and dog3 are Dog object and assume they are created with rules of dogSchema. So yes, we can pass an array as a parameter in insertMany( ).

Up until now, we were using find( ) method in mongo shell to retrieve documents. What if we want to have them in our code? Say we need to filter some documents, play with them, and update them. To achieve this, we can use find( ) method in app.js as well. Syntax will be a bit different than the previous one. Check below.

11. Find in Mongoose

Dog.find({query}, function(err, foundList){});

As a first parameter you can filter the documents with query operators. The second parameter is a callback function which gives you the error if there is any, or gives you the list of the results. So, foundList is the result of the find operation. Since this is a find all function, the result will be an array of items that matches the query. If we left the curly brackets({}) blank as it is, it will return all of the documents. Then, you can play with foundList inside your js file.

12. Validation in Mongoose

const dogSchema = new mongoose.Schema({

name {

type: String,

required: true

},

age: Number,

breed: String

});

If you want to restrict the fields of the documents like the example above, you can do that by specifying it into the schema. By setting required attribute as true, we no longer allow dogs without a name. We could be more specific. For instance we could put a min and max value for age attribute.

13. Min-Max Validation