- First, make sure you have MongoDB and Node.js installed.
- Next install Mongoose from the command line using npm:
How to Connection of Mongoose in Node Js.

Rukon Uddin
Technical deep diveAugust 25, 20241$ npm install mongoose - save
Now let’s say we like obscure kittens and want to record every kitten we see on MongoDB. The first thing we need to do is to include Mongoose in our project and open a link to the test database in the locally running example of MongoDB.
1// getting-started.js23 const mongoose = require('mongoose');4 main().catch(err => console.log(err));56 async function main() {7 await mongoose.connect('mongodb://localhost:27017/test');}8 }
For brevity, let’s assume that all of the following code is in the main () function. With mangoes, everything originates from a schema. Let’s get a reference and define our kitten.
1const kittySchema = new mongoose.Schema({2 name: String3 });
So far so good. We’ve got a schema with a property, name, which would be a string. The next step is compiling our schema into a model..
1const Kitten = mongoose.model('Kitten', kittySchema);
A model is a class with which we create documents. In this case, each document will be a kitten with features and behaviors declared as our schema. Let’s make a kitten document that the little guy we just met on the sidewalk outside:
1const silence = new Kitten({ name: 'Silence' });2 console.log(silence.name);34 // 'Silence' Kittens can do magic too, so let's take a at how to add "Speak"5 functionality to our document:67 kittySchema.methods.speak = function speak() {89 const greeting = this.name ? "Meow name is " + this.name : "I don't have a name";1011 console.log(greeting);12 };
1const Kitten = mongoose.model('Kitten', kittySchema);
Functions added to a schema method property are compiled into model prototypes and expressed in examples of each document:
1const fluffy = new Kitten({ name: 'fluffy' });2 fluffy.speak()
We’re talking kittens! But we still can’t save anything on MongoDB. Each document can be saved in the database by calling the save method. The first argument of callback would be an error if anything happened.
1await fluffy.save();2fluffy.speak();
Say time goes by and we want to show all the kittens we see. We can access all kitten documents through our Kitten model.
1const kittens = await Kitten.find();2 console.log(kittens);
We’ve just logged the kittens into our DB console. If we want to filter the names of our kittens, Mongoose MongoDBs support rich query syntax.
1await Kitten.find({ name: /^fluff/ });
It does a search for all documents, including the property of a name beginning with “Fluff” and returns the result as an array of kittens in the callback.
Enjoyed the article?
Drop a love to let me know
Comments (0)
No comments yet
Be the first to comment!
Please login to join the conversation.
Read more deep dives
Notes from the trenches — architecture decisions, debugging stories, and the small wins that compound.
Browse all articles