⚫ SETTING UP YOUR NODEJS PROJECT

A Practical Introduction to Setting Up a NodeJs+Express web project with VSCode
McCauley™ ・ Nov 23 '20 ・ 3 min read
#javascript
#expressjs
#node
#newbie
Or you can download the Project Setup from my GitHub repo
🌓 TERMINOLOGIES USED
- Model: A Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc. -FCC
- Schema: A Mongoose schema defines the structure of the document, default values, validators, etc. -FCC
- 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
andEJS
modules
>> 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
const mongoose = require("mongoose")
var connectionUrl = "mongodb://localhost:27017/databasename"
- 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")
})
🎯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}`)
})
🌕 STEP 2 of 3
- Create a new folder
models
- 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")
📌 Create a Schema variable and assign it the Schema class from mongoose
const Schema = mongoose.Schema
📌 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"]
}
})
📌 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
📌 Export the model
module.exports = UserModel
🎯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
🌕 STEP 3 of 3
- Create a new folder
views
- In the views folder, create an
index.ejs
file - 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>
- 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}))
📌 Set the view engine to ejs
app.set("view engine", "ejs")
📌 Create a route for displaying the html form we created
app.get("/index", (req, res)=>{
res.render("index")
})
📌 Import the userModel from the models folderImport the userModel from the models folder
const UserModel = require("./models/user")
📌 Create a route/endpoint for collecting and sending the user inputs to our Mongo DataBase
app.post("/api/user", (req, res)=>{
})
📌 In the endpoint, Instantiate the UserModel and pass the req.body as an argument.
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:
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:
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")
})
Top comments (4)
Thank you for sharing
Please review this your code especially in the index.js. It didn't work.
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!
It showing error of UserModel is not a constructor.Please help to get out of this..