Accepting Data From a Form And Saving It To MongoDB through Mongoose
Tags: mongodb, node, express, beginners
Published: 2020-12-28 03:07:16

# **⚫ SETTING UP YOUR NODEJS PROJECT**
{% post mccauley/a-practical-introduction-to-setting-up-a-nodejs-express-web-project-with-vscode-220h %}
**Or you can download the Project Setup from my GitHub repo**
{% github mack-code0/NodeJs-App %}

### **🌓 TERMINOLOGIES USED**
1. **Model:** A Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc. *-FCC*
2. **Schema:** A Mongoose schema defines the structure of the document, default values, validators, etc. *-FCC*
3. **Mongoose:** Mongoose is an object data modeling (ODM) library that provides a rigorous modeling environment for your data, enforcing structure as needed while still maintaining the flexibility that makes MongoDB powerful *-DevCenter*

### **🌕 STEP 1 of 3**
* Open your terminal and make sure it's navigated to the Project Folder
* Enter the command below in the terminal to install the ``Mongoose`` and ``EJS`` modules
```javascript
>> npm i mongoose ejs
```
* In your ``index.js`` file, require the mongoose module, and also create a variable that'll hold the database connection url
```javascript
const mongoose = require("mongoose")
var connectionUrl = "mongodb://localhost:27017/databasename"
```
* Still in the ``index.js`` file, Establish a connection using the connection url
```javascript
mongoose.connect(connectionUrl, {useNewUrlParser: true, useUnifiedTopology: true}, (err)=>{
    if(err) throw err
    console.log("Connected")
})
```
## 🎯Summary of ``index.js`` file:
```javascript
const express = require('express')
const app = express()
const mongoose = require("mongoose")
var connectionUrl = "mongodb://localhost:27017/databasename"
mongoose.connect(connectionUrl, {useNewUrlParser: true, useUnifiedTopology: true}, (err)=>{
    if(err) throw err
    console.log("Connected")
})

app.get("/home", (req, res)=>{
    res.send("Hello")
})

const port = process.env.PORT || 4000
app.listen(port, ()=>{
    console.log(`Listening to Port ${port}`)
})
```
---

### **🌕 STEP 2 of 3**
* Create a new folder `` models ``
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/aznfp114yi7wjajt8s4x.jpg)
* In the **models** folder, create a ``user.js`` file
* The following steps will be done in the ``user.js`` file:

#####**📌 Require the mongoose module**
```javascript
const mongoose = require("mongoose")
```
#####**📌 Create a Schema variable and assign it the Schema class from mongoose**
```javascript
const Schema = mongoose.Schema
```
#####**📌 Instantiate the Schema class and pass in your document structure as an argument to the schema class**
```javascript
const UserSchema = new Schema({
    firstname: {
        type: String,
        required: [true, "Firstname is required"]
    }, 
    lastname: {
        type: String,
        required: [true, "Lastname is required"]
    }
})
```
#####**📌 Create a mongoose model with the preffered name of your ``collection`` and the UserSchema created above**
```javascript
const UserModel = mongoose.model("user", UserSchema)
// The String "user" above is the name of your collection
```
#####**📌 Export the model**
```javascript
module.exports = UserModel
```
## 🎯Summary of ``user.js`` file:
```javascript
const mongoose = require('mongoose');
const Schema = mongoose.Schema

const UserSchema = new Schema({
    firstname: {
        type: String,
        required: [true, "Firstname is required"]
    }, 
    lastname: {
        type: String,
        required: [true, "Lastname is required"]
    }
})

const UserModel = mongoose.model("user", UserSchema)
module.exports = UserModel
```
---

### **🌕 STEP 3 of 3**
* Create a new folder `` views ``
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xyskqt0u9gvax520drn3.jpg)
* In the views folder, create an ``index.ejs`` file
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/spa6vc9rktqk4uf0qu1g.jpg)
* Create a simple **html form** in the ``index.ejs`` file with the **method** attribute set to *POST* and the **action** attribute set to ``/api/user``
```html
<html>
    <body>
        <form method="POST" action="/api/user">
            <label for="">Firstname</label>
            <input type="text" name="firstname" id=""><br>
            <label for="">Lastname</label>
            <input type="text" name="lastname" id=""><br>
            <input type="submit">
        </form>
    </body>
</html>
```
* The following steps will be done in the ``index.js`` file:

#####**📌 Create a body parsing middleware with the built in __express body-parser__ in order to populate the ``req.body`` with our inputs**
```javascript
app.use(express.urlencoded({extended: true}))
```
#####**📌 Set the view engine to ``ejs``**
```javascript
app.set("view engine", "ejs")
```
#####**📌 Create a route for displaying the __html form__ we created**
```javascript
app.get("/index", (req, res)=>{
    res.render("index")
})
```
#####**📌 Import the userModel from the models folderImport the userModel from the models folder**
```javascript
const UserModel = require("./models/user")
```
#####**📌 Create a route/endpoint for collecting and sending the user inputs to our Mongo DataBase**
```javascript
app.post("/api/user", (req, res)=>{

})
```
#####**📌 In the endpoint, Instantiate the UserModel and pass the req.body as an argument.**
```javascript
    const SaveUser = new UserModel(req.body)
```
######**Note:** The req.body holds the user inputs sent from the form.

#####__📌 Save the UserInput to your database by adding the following lines of code to the endpoint:__
```javascript
        SaveUser.save((error, savedUser)=>{
        if(error) throw error
        res.json(savedUser)
```
######**NOTE:** The conditions in the save method is simply saying: If an error is encountered, throw the error. But if there is no error, return the saved user details.

## 🎯Updated Summary of ``index.js`` file:
```javascript
const express = require('express')
const app = express()
const mongoose = require("mongoose")
const UserModel = require("./models/user")
var connectionUrl = "mongodb://localhost:27017/dbname"
mongoose.connect(connectionUrl, {useNewUrlParser: true, useUnifiedTopology: true}, (err)=>{
    if(err) throw err
    console.log("Connected")
})

app.use(express.urlencoded({extended: true}))
app.set("view engine", "ejs")

app.get("/home", (req, res)=>{
    res.render("index")
})

app.post("/api/user", (req, res)=>{
    const SaveUser = new UserModel(req.body)
    SaveUser.save((error, savedUser)=>{
        if(error) throw error
        res.json(savedUser)
    })
})

app.listen(9000, ()=>{
    console.log("listening to port 9000")
})
```
###*__>>>__ If your data was successfully saved, an object will be returned to you after submitting the form.*


---

#__🏁 Having any Question or Suggestion? Drop them in the discussion section below. 👇__