Installing Express and Mongoose-
- Install the required libraries by running the command:
npm i express
npm i mongoose
Connecting to a Database:
Install nodemon by the following command and answer some basic questions:
npm i -D nodemon
Make two files index.js and db.js
Inside db.js , Connect to MongoDB using
mongoose.connect
method. This method takes a connection string as the first parameter and options as the second parameter. Here's an example of connecting to MongoDB:const connectToMongo = () => { const mongoose = require("mongoose"); const Url = 'mongodb://localhost:27017'; mongoose.connect(Url, { useNewUrlParser: true }) .then(() => { console.log("connected to database mongodb"); }) .catch((err) => { console.log("Error", err); }); };
- Don't forget to export this function ,then In your index.js file add the following command:
module.exports = connectToMongo;
//index.js const connectToMongo = require('./db'); connectToMongo();
That's it you are successfully connected to MongoDB.
Setup Express Server:
Here are the basic steps to set up an Express server:
Install Express by running the command
npm install express
in your project directory.Create a new file in your project directory called
index.js
Import the Express library at the top of your
index.js
file using the following code:const express = require('express');
Create a new instance of the Express application by calling the
express()
method :const app = express();
Define a route by calling one of the HTTP methods (e.g.
app.get()
,app.post
()
,app.put()
, etc.) on your app object. Here's an example of defining a route for the root path of your application:app.get('/', (req, res) => { res.send('Hello, World!'); });
Start the server by calling the
listen()
method on your index object. This method takes a port number and an optional callback function as parameters. Here's an example of starting the server on port 3000:const port = 3000; app.listen(port, () => { console.log(`Server started on port ${port}`); });
Run your server by executing the
node index.js
command in your terminal.
That's it! You now have a basic Express server set up that will respond with "Hello, World!" when you navigate to the root path of your application in a web browser or make a GET request to the root path using a tool like Postman, cURL or thunderclient. You can add additional routes, middleware, and functionality to your server as needed to build out your application.