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)

--

--

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