javascript CRUD操作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript CRUD操作相关的知识,希望对你有一定的参考价值。
//========= POST ========//
// Process Form
app.post('/ideas', (req, res) => {
let errors = [];
// Add Server-Side Validation
if (!req.body.title) {
errors.push({
text: 'Please add a title'
});
}
if (!req.body.details) {
errors.push({
text: 'Please add some details'
});
}
// Check if there are errors
if (errors.length > 0) {
// Render back html page to send error messages
res.render('ideas/add', {
errors,
title: req.body.title,
details: req.body.details
})
} else {
const newUser = {
title: req.body.title,
details: req.body.details
}
// Don't just fucking insert the request body in here.
// It's not a good idea
new Idea(newUser)
.save()
.then(idea => {
res.redirect('/ideas');
})
}
});
//===== END POST ====//
//========= GET ========//
// Edit Idea Form
app.get('/ideas/edit/:id', (req, res) => {
Idea.findOne({ _id: req.params.id })
.then(idea => {
res.render('ideas/edit', {
title: idea.title,
details: idea.details
})
})
});
app.get('/ideas', (req, res) => {
Idea.find({})
.sort({ date: 'desc' })
.then(ideas => {
res.render('ideas/index', {
ideas
})
})
})
//===== END GET ====//
//========= PUT ========//
// Note: method-override is needed in non-supported clients
// method-override lets you use HTTP verbs such as PUT or DELETE in places where the client doesn't support it.
app.put('/ideas/:id', (req, res) => {
Idea.findOne({
_id: req.params.id
}).then(idea => {
// new values
idea.title = req.body.title;
idea.details = req.body.details;
idea.save().then(idea => {
res.redirect('/ideas');
})
})
})
//===== END PUT ====//
//========= DELETE ========//
app.delete('/ideas/:id', (req, res) => {
Idea.remove({ _id: req.params.id })
.then(() => {
res.redirect('/ideas');
})
})
//===== END DELETE ====//
以上是关于javascript CRUD操作的主要内容,如果未能解决你的问题,请参考以下文章
AWS - JavaScript - 具有经过身份验证的 Cognito 用户对 DynamoDB 的 CRUD 操作
javascript 用于在模型上执行CRUD操作的自定义URL
如何通过从 aspx.cs 文件中获取参数来执行数据库 CRUD 操作?
基于 flask-socketio 的 CRUD 操作初探
javascript CRUD请求表达
javascript nodejs-crud实践