DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Accepting Data From a Form And Saving It To MongoDB through Mongoose
Macaulay Uzu
Macaulay Uzu

Posted on

Accepting Data From a Form And Saving It To MongoDB through Mongoose

⚫ SETTING UP YOUR NODEJS PROJECT


Or you can download the Project Setup from my GitHub repo

πŸŒ“ 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
>> npm i mongoose ejs
Enter fullscreen mode Exit fullscreen mode
  • In your index.js file, require the mongoose module, and also create a variable that'll hold the database connection url
const mongoose = require("mongoose")
var connectionUrl = "mongodb://localhost:27017/databasename"
Enter fullscreen mode Exit fullscreen mode
  • Still in the index.js file, Establish a connection using the connection url
mongoose.connect(connectionUrl, {useNewUrlParser: true, useUnifiedTopology: true}, (err)=>{
    if(err) throw err
    console.log("Connected")
})
Enter fullscreen mode Exit fullscreen mode

🎯Summary of index.js file:

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}`)
})
Enter fullscreen mode Exit fullscreen mode

πŸŒ• STEP 2 of 3

  • Create a new folder models Alt Text
  • In the models folder, create a user.js file
  • The following steps will be done in the user.js file:
πŸ“Œ Require the mongoose module
const mongoose = require("mongoose")
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Create a Schema variable and assign it the Schema class from mongoose
const Schema = mongoose.Schema
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Instantiate the Schema class and pass in your document structure as an argument to the schema class
const UserSchema = new Schema({
    firstname: {
        type: String,
        required: [true, "Firstname is required"]
    }, 
    lastname: {
        type: String,
        required: [true, "Lastname is required"]
    }
})
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Create a mongoose model with the preffered name of your collection and the UserSchema created above
const UserModel = mongoose.model("user", UserSchema)
// The String "user" above is the name of your collection
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Export the model
module.exports = UserModel
Enter fullscreen mode Exit fullscreen mode

🎯Summary of user.js file:

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
Enter fullscreen mode Exit fullscreen mode

πŸŒ• STEP 3 of 3

  • Create a new folder views Alt Text
  • In the views folder, create an index.ejs file Alt Text
  • 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>
    <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>
Enter fullscreen mode Exit fullscreen mode
  • 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
app.use(express.urlencoded({extended: true}))
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Set the view engine to ejs
app.set("view engine", "ejs")
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Create a route for displaying the html form we created
app.get("/index", (req, res)=>{
    res.render("index")
})
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Import the userModel from the models folderImport the userModel from the models folder
const UserModel = require("./models/user")
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ Create a route/endpoint for collecting and sending the user inputs to our Mongo DataBase
app.post("/api/user", (req, res)=>{

})
Enter fullscreen mode Exit fullscreen mode
πŸ“Œ In the endpoint, Instantiate the UserModel and pass the req.body as an argument.
    const SaveUser = new UserModel(req.body)
Enter fullscreen mode Exit fullscreen mode
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:
        SaveUser.save((error, savedUser)=>{
        if(error) throw error
        res.json(savedUser)
Enter fullscreen mode Exit fullscreen mode
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:

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")
})
Enter fullscreen mode Exit fullscreen mode

>>> 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. πŸ‘‡

Top comments (3)

Collapse
dreamchild7 profile image
dreamchild7

Please review this your code especially in the index.js. It didn't work.

Collapse
zelal profile image
Zelal Hossain • Edited on

Thank you for sharing

Collapse
chrisblanc profile image
iamchrisblanc

Macaulay,
Thank you so much for taking the time to post this. It was everything I was looking for to solve my misunderstanding. You are awesome!

Head to your account's Settings to...

🌚 Enable dark mode
πŸ”  Change your default font
πŸ“š Adjust your experience level to see more relevant content