1. Express Js CRUD Tutorial using mongodb.(create)

  1. Create model:
vim user_model.js=======================code==================
const { Schema, model } = require('mongoose')
//New Schema toiri kori
const userSchema = new Schema({
title:{
type: String,
required: true,
trim: true
},
description: {
type: String,
required: true,
trim: true
}
})
const user_table = model('user_table',userSchema)//create user_tablemodule.exports = user_table

2. Create form:

vim home.ejs====================code==========================
<!doctype html>
<html lang="en">
<head>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<h1>Hello, world!</h1>
<form action="/user_create" method="POST">
<input type="text" name="title">
<textarea name="description"></textarea>
<input type="submit" class="btn btn-success" value="Submit">
</form>

</body>
</html>

3. Create Controller:

vim homeController.js==================code=========================const user_model = require('./user_model')exports.createUserGetController = (req, res, next) => {
res.render('home')
}
exports.createUserPostController = async (req, res, next) => {
//console.log(req.body)
//res.send(req.body)
let {title,description,options} = req.bodylet user = new user_model({
title,
description
})
try{await user.save() //save data,async for await
res.redirect('/')
} catch (e) {
console.log(e)
}
}

app.js

const allController = require('./homeController')app.get('/', allController.createUserGetController)
app.post('/user_create', allController.createUserPostController)

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Javascript-In Present Era.

What does error say? (keep updating)

Material UI and Material UI Icons

Create Stopwatch using javascript

Importance of Memento Design Pattern

How to inspect dynamic dropdown WebElements?

What is better for HTTP Requests: Fetch or Axios Comparison

React-Redux, A Love & Hate Story In 2021

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Safaetul Ahasan

Safaetul Ahasan

Software Engineer

More from Medium

Create Node js-express API from Scratch

Fetching data from an API using Axios

Mean Girls, GET in loser, we’re fetching with axios

Creating a Web Server With Node.js using HTTP Module and Logging the Requests.

Google Drive API, Resumable upload — Javascript