Mongoose is an ODM (Object Document Mapper) that allows users to conveniently create and manage data in MongoDB. While it is possible to manage data, define schemas, etc. using MongoDB APIs, it is quite difficult to do so. Hence, Mongoose has made lives easier.
When using Mongoose sometimes errors can occur and we don’t know the reason for it and we go through the code again and again trying different ways to solve it. However, the problem may lie in the installation of the module.
In this article, we will see multiple ways to check if Mongoose is installed on your project with some simple examples.
Also Read: Difference Between MongoDB vs Mongoose
How to Check if Mongoose is Installed in Node.js?
- Open a terminal and execute the below command to create a project directory, then, move into it:
mkdir mongooseCheck
cd mongooseCheck
- Create a new Node.js project along with the entry point file using the following commands:
npm init -y
touch index.js
You will now see a package.json file created automatically for you.
- Install the Mongoose and Express package in your Nodejs project:
npm i mongoose express
after this, you should see node_modules created automatically for you. Let us now proceed to check whether Mongoose has been installed.
Method 1: By Checking the package.json File
- Open up the package.json file.
- Look for the “dependencies” property which is an object, in the file.
- Try to look for the “mongoose” property inside the dependencies.
This is what the package.json looks like:
{
"name": "shoe-store",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Aneesha S",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongoose": "^5.11.17"
}
}
If the attribute “mongoose” is present then it means that Mongoose has been installed successfully. Apart from this, you can also check your Mongoose version number via its key value.
Method 2: By Checking the node_modules Directory
In the project directory, pull down the node_modules directory. Here, you will see multiple directories with the package name you have installed along with some of the ones you didn’t.
Find the directory named “mongoose”. This is the directory where all the Mongoose files for your project reside. If this directory exists it means Mongoose is already installed, this option is very handy.
Method 3: By Connecting to MongoDB and Inserting Documents
If for some reason you are unable to perform the above steps or if the above methods didn’t work for you, then the last method you can go to check if Mongoose is installed is to connect to MongoDB. Let’s see an example, let’s create a schema, insert a few documents and check if Mongoose is installed or not.
Creating a Model using Mongoose
- Create a model folder inside your project directory.
- Now, create a file for your model. Let’s name it shoes.js.
- Inside the shoes.js file, import the Mongoose package and create a data schema as shown below:
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
name: {
type: String,
},
price: {
type: Number,
},
size: {
type: Number
},
style: {
type: String,
},
onSale: {
type: Boolean
},
freeDelivery: {
type: Boolean
}
})
- Create the model using the model() function by passing the schema as an argument so that MongoDB can create a ‘shoes’ collection. Then, export the created model:
const Shoe = mongoose.model('Shoe', productSchema);
module.exports = Shoe;
Connecting to the MongoDB Database using Mongoose
- Open the index.js file and import Mongoose and the created model. Then, connect Mongoose to a local MongoDB database using the connect() function:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const Shoe = require('./models/product.js');
mongoose.connect('mongodb://localhost:27017/shoeStore', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log(`CONNECTED TO MONGO USING MONGOOSE!`);
})
.catch((err) => {
console.log(`OH NO! MONGOOSE MONGO CONNECTION ERROR!`);
console.log(err);
})
We have now connected the Node.js application to a MongoDB database, named ‘shoeStore’.
Inserting Data using Mongoose
- Now let’s try to insert some data in the ‘shoeStore’ collection by using the insertMany() function which is used to insert multiple documents.
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const Shoe = require('./models/product.js');
mongoose.connect('mongodb://localhost:27017/shoeStore', { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => {
console.log(`CONNECTED TO MONGO USING MONGOOSE!`);
})
.catch((err) => {
console.log(`OH NO! MONGOOSE MONGO CONNECTION ERROR!`);
console.log(err);
})
const seedProducts = [
{
"name": "Mariana Grider Boots",
"price": 23000,
"size": 7,
"style": "Slingbacks",
"onSale": false,
"freeDelivery": true
},
{
"name": "Purple Shimmery Heels",
"price": 13380,
"size": 6,
"style": "Peep Toes",
"onSale": true,
"freeDelivery": false
},
{
"name": "Zac Porter Straps",
"price": 19760,
"size": 8,
"style": "Ankle Strap",
"onSale": true,
"freeDelivery": true
},
{
"name": "Valerina's Red Carpet Toes",
"price": 26000,
"size": 9,
"style": "Scarpin",
"onSale": false,
"freeDelivery": false
},
{
"name": "Neeta Parmar's Stylish Bees 'n' Honey Boots",
"price": 10780,
"size": 7,
"style": "Wedge Booties",
"onSale": true,
"freeDelivery": true
}
]
Shoe.insertMany(seedProducts)
.then(d => console.log(d))
.catch(err => console.log(err))
Run the Application
- Open the command prompt or terminal, locate the project directory and run the index.js file:
node index.js
- This is what our console prints:
(node:996) Warning: Accessing non-existent property 'MongoError' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
(node:996) DeprecationWarning: Listening to events on the Db class has been deprecated and will be removed in the next major version.
CONNECTED TO MONGO!
[
{
_id: 616b18a556e71503e4a0334d,
name: 'Mariana Grider Boots',
price: 23000,
size: 7,
style: 'Slingbacks',
onSale: false,
freeDelivery: true,
__v: 0
},
{
_id: 616b18a556e71503e4a0334e,
name: 'Purple Shimmery Heels',
price: 13380,
size: 6,
style: 'Peep Toes',
onSale: true,
freeDelivery: false,
__v: 0
},
{
_id: 616b18a556e71503e4a0334f,
name: 'Zac Porter Straps',
price: 19760,
size: 8,
style: 'Ankle Strap',
onSale: true,
freeDelivery: true,
__v: 0
},
{
_id: 616b18a556e71503e4a03350,
name: "Valerina's Red Carpet Toes",
price: 26000,
size: 9,
style: 'Scarpin',
onSale: false,
freeDelivery: false,
__v: 0
},
{
_id: 616b18a556e71503e4a03351,
name: "Neeta Parmar's Stylish Bees 'n' Honey Boots",
price: 10780,
size: 7,
style: 'Wedge Booties',
onSale: true,
freeDelivery: true,
__v: 0
}
]
Looking at the above output we can say that we have successfully connected to Mongo with the help of Mongoose. Now, we will check the MongoDB database for the documents.
- Now, open the Mongo shell, list out all databases and choose the one we just created:
show dbs
use shoeStore
- Now, list all collections:
show collections
shoes
Use this collection because this is what Mongoose has instructed Mongo to create.
- We will now check if the documents were created or not using the below query:
> db.shoes.find({}).pretty()
{
"_id" : ObjectId("616b18a556e71503e4a0334d"),
"name" : "Mariana Grider Boots",
"price" : 23000,
"size" : 7,
"style" : "Slingbacks",
"onSale" : false,
"freeDelivery" : true,
"__v" : 0
}
{
"_id" : ObjectId("616b18a556e71503e4a0334e"),
"name" : "Purple Shimmery Heels",
"price" : 13380,
"size" : 6,
"style" : "Peep Toes",
"onSale" : true,
"freeDelivery" : false,
"__v" : 0
}
{
"_id" : ObjectId("616b18a556e71503e4a0334f"),
"name" : "Zac Porter Straps",
"price" : 19760,
"size" : 8,
"style" : "Ankle Strap",
"onSale" : true,
"freeDelivery" : true,
"__v" : 0
}
{
"_id" : ObjectId("616b18a556e71503e4a03350"),
"name" : "Valerina's Red Carpet Toes",
"price" : 26000,
"size" : 9,
"style" : "Scarpin",
"onSale" : false,
"freeDelivery" : false,
"__v" : 0
}
{
"_id" : ObjectId("616b18a556e71503e4a03351"),
"name" : "Neeta Parmar's Stylish Bees 'n' Honey Boots",
"price" : 10780,
"size" : 7,
"style" : "Wedge Booties",
"onSale" : true,
"freeDelivery" : true,
"__v" : 0
}
Great! Mongoose has successfully created and inserted a set of documents into the MongoDB database. This proves Mongoose is successfully installed and is working properly.
If you find using Mongo Shell hard, you can use the MongoDB compass to check for inserted documents.
Check MongoDB Version
If your Mongoose module is properly installed and still you are having some errors, you can check the MongoDB server version by navigating to the directory where it is installed using the command line or shell and then running the “mongod –version” command. This will return a version that you can compare with the versions the Mongoose module is compatible with.
Read More: NodeJS Interview Questions and Answers
Conclusion
In this article, we have seen three ways to check whether Mongoose is installed, the first is by checking the package.json file, the second is by checking the node_modules directory and the third is by connecting to MongoDB and inserting the documents. There may be some other way too like using the “npm list” command or console logging the “mongoose.version”. You can use any way that suits you best. Hope this guide on how to check if your Node.js application has Mongoose installed or not was helpful!
References
- How to check if Mongoose (MongoDV) is installed or not – Stack Overflow
- How to Check Your Mongoose Version – Mongoose Official Docs