InterviewSolution
| 1. |
How to Define Models in Express JS? |
|
Answer» Models are required in Express JS, when we are INTEGRATING Express with databases, especially MongoDB databases. It defines the way in which the data will be stored in the MongoDB database. Let us understand it through an example. We will first create a new directory, then change directory and initialize a Node project with the npm init -y command. After that we also need to install the package of express and mongoose. Next, we need MongoDB running from the cloud or local system. We have the local MongoDB running on our system and showing through COMPASS. Now, create a file SERVER.js and here, we shall first import express and mongoose. After that, we shall create a simple GET route. Next, we will USE mongoose to connect to our local running database through mongoose.connect(). Now, we are using mongoose.CONNECTION.once() to open the database connection and show the success or the error messages, depending on the status. Finally listening to incoming requests on port 3000. Now, in the terminal run the server by node server.js command and we will see the message that it was able to connect to the database successfully. Now, we will create our model for the database. So, create a folder Models in the root directory and create a file emp.js in it. Here, we are creating a schema for the employee which basically contains the structure. So, we have empName and empEmail in the schema. Now, we will use this Model in our server.js file. We need to import the Model first and also use the express.json(), because we are going to send json data. Next, create a POST route to add the employees. Here, we are using our model to send the empName and empEmail. After that we are using emp.save() to save the data in the MongoDB database. Now, we will send the POST request from Postman as JSON object and it will be a success. We can also check in MongoDB Compass to see if the data got saved successfully. |
|