Connect Nodejs project to MongoDB using mongoose
Hi!
Welcome to the second article in my series.
Now that we have done setting up our project as described in my previous article, Let's connect our project to MongoDB using mongoose. You can download the initial code from my github.
First up, download MongoDB from their official website (I'm using mongo 4.4 stable version for the project) and install the application on your machine. Now run the mongodb service on your machine using terminal by running below command
mongod
Now that MongoDB service is up and running on your machine, let's connect our project to the database using mongoose. For that install mongoose dependency in your project. Go to the terminal and type the command below
npm i mongoose
npm i -D @types/mongoose
After you're done installing the dependencies, open index.ts file and import mongoose module
import mongoose from "mongoose";
Now to make sure you follow best practices, keep all the imports at the top of your file. And write the code below before the server creation.
mongoose.connect("mongodb://localhost:27017/item-manager").then((connection) => {
console.log(`connected to MongoDB at mongodb://localhost:27017/item-manager`);
});
Your index.ts file should look something like this
If everything's fine you will see the log that connected to mongoDB. If you get an error like I did, then don't worry.
This error is because of the node version, check your node version using command
node -v
Upgrade your node version to 14 at least using command line nvm install
nvm install 14
After installation is done switch to version 14 using command
nvm use 14
And now run your project using command
npm run dev
And you see the below in terminal