gpt4 book ai didi

javascript - lowdb 添加/编辑/更新/删除成功,但需要使用 if/then/else 语句对更新部分进行一些更改

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:20 25 4
gpt4 key购买 nike

我已经使用express和lowdb数据库完成了添加/删除/编辑/更新代码,但它非常基本,尤其是在更新部分,而我想使用if/then/else语句,但我的小脑袋做不到独自一人;代码如下:

/* Update the data from displayed table of editup.pug */
router.post('/update', (req, res, next) => {
db.read(); //read current datas in db
let uid = req.body.id; // transfer "id" from TABLE to "uid"
/* Do actual updation of User via ID */
db.get('users')
.find({id: uid})
.assign({First_Name: req.body.First_Name})
.assign({Middle_Name: req.body.Middle_Name})
.assign({Last_Name: req.body.Last_Name})
.assign({Email: req.body.Email})
.write();
/* Do actual updation of User via ID ends here */
res.status(200);
res.redirect('/');
});

完整代码如下:

app.js

var port = 3000
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var logger = require('morgan');

var indexRouter = require('./routes/index');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};

// render the error page
res.status(err.status || 500);
res.render('error');
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

index.js

var express = require('express');
var router = express.Router();
var shortid = require('shortid');

var low = require('lowdb');
var FileSync = require('lowdb/adapters/FileSync');
var adapter = new FileSync('./DBase/shortIdDB.json');
var db = low(adapter);

// default user list
db.defaults({ users: [] }).write();

/* GET data listing. Display list of current data in table */
router.get('/', (req, res, next) => {
db.read(); //read current datas in db
var putusers=db.get('users'); // use 'users:' section of db
var data = putusers.value(); // transfer values from getusers to data
res.render('index', { data }); // Send values from data to Table
console.log('Your Datas:', data);
});

// Form post -- Start adding data from FORM to DB
router.post('/add', (req, res) => {
db.read(); //read current datas in db
/* start collecting data from FORM */
var FormFeed = {
id: shortid.generate(),
First_Name: req.body.FName,
Middle_Name: req.body.MName,
Last_Name: req.body.LName,
Email: req.body.EMail};
/* collect data from FORM end here */
db.get('users').push(FormFeed).write(); // push and write to the db
res.redirect('/');
});

// delete selected record via id
router.get('/delete', function(req, res) {
db.read(); //read current datas in db
let uid = req.query.id; // transfer "id" from TABLE to "uid"
let data = db.get('users').find({ id: uid }).value(); // find and collect data via "uid"
console.log("User to Process: ", data, "and the id: ", uid);
/* Do actual deletion of User via ID */
db.get('users')
.remove({ id: uid })
.write();
/* Do actual deletion of User via ID End here!!! */
res.status(200);
res.redirect('/');
});

/* GET data via ID to update and display data in table */
router.get('/toupdate', (req, res, next) => {
db.read(); //read current datas in db
let uid = req.query.id; // transfer "id" from TABLE to "uid"
let dataup = db.get('users').find({ id: uid }).value(); // find and collect data via "uid"
console.log("User to Process: ", dataup, "and the id: ", uid);
res.render('editup', { dataup }); // Send values from data to Table
});

/* Update the data from displayed table of editup.pug */
router.post('/update', (req, res, next) => {
db.read(); //read current datas in db
let uid = req.body.id; // transfer "id" from TABLE to "uid"
/* Do actual updation of User via ID */
db.get('users')
.find({id: uid})
.assign({First_Name: req.body.First_Name})
.assign({Middle_Name: req.body.Middle_Name})
.assign({Last_Name: req.body.Last_Name})
.assign({Email: req.body.Email})
.write();
/* Do actual updation of User via ID ends here */
res.status(200);
res.redirect('/');
});

module.exports = router;

index.pug

extends layout
block content
.container
h2 NodeJs Express LowDB - View Add, Edit/Update, Delete records
.success
.error
form(id='form1' method='post')
input#id(type='hidden', name='id', value='')
table
tr
td(style='text-align: center')
input#First_Name(type='text',name='FName', placeholder='First Name', value='')
|      
input#Middle_Name(type='text',name='MName', placeholder='Middle Name', value='')
|      
input#Last_Name(type='text',name='LName', placeholder='Last Name', value='')
|      
input#Email(type='text',name='EMail', placeholder='Email Address', value='')
|      
input#subbtn(type="submit" onclick="javascript: form.action='/Add'" Value='Add')

tbody
table
tr
th id
th First Name
th Middle Name
th Last Name
th Email
th(colspan='2') Action
each users in data
tr
td= users.id
td= users.First_Name
td= users.Middle_Name
td= users.Last_Name
td= users.Email
td(id="tdclck1"): a(href='http://localhost:3000/toupdate?id='+users.id) Edit
td(id="tdclck2"): a(href='http://localhost:3000/delete?id='+users.id) Delete

editup.pug

extends layout
block content
.container
h2 NodeJs Express LowDB - View Add, Edit/Update, Delete records
.success
.error
form(id='form2' method='post')
table
tr
th id
th First Name
th Middle Name
th Last Name
th Email
th Action
tr()
td()
input(type='text',name='id',readonly,value=dataup.id)
td()
input(type='text',name='First_Name',value=dataup.First_Name)
td()
input(type='text',name='Middle_Name',value=dataup.Middle_Name)
td()
input(type='text',name='Last_Name',value=dataup.Last_Name)
td()
input(type='text',name='Email',value=dataup.Email)
td
input#subbtn(type="submit" onclick="javascript: form.action='/Update'" Value='Update')
a(href="/") << back

shotidDB.json

{
"users": [
{
"id": "-34BAqsS",
"First_Name": "Kauna-unahan",
"Middle_Name": "Kagitna-ginaan",
"Last_Name": "Kahuli-hulihan",
"Email": "sdfg@sdfv.dfc"
},
{
"id": "wtWsbepJ",
"First_Name": "Pangalan",
"Middle_Name": "GitnangPangalan",
"Last_Name": "HulingPangalan",
"Email": "kljjl123@ooo.com"
},
{
"id": "zyBMsLtJ",
"First_Name": "Kalatsa",
"Middle_Name": "palitsako",
"Last_Name": "ayooo",
"Email": "walay.ayo@abc.com"
},
{
"id": "vxqDSrPm",
"First_Name": "newuser",
"Middle_Name": "newmid",
"Last_Name": "newlast",
"Email": "newmail@mail.com"
},
{
"id": "ybl4yvNS",
"First_Name": "Kaunaunahan Ngalan",
"Middle_Name": "Kagitnagitnaan Pangalan",
"Last_Name": "Apelyido",
"Email": "kakaape@email.ph"
}
]
}

我已经设法更改了实现 if/else 语句的更新部分,代码如下:

/* Update the data from displayed table of editup.pug Revision 1 */
router.post('/update', (req, res, next) => {

db.read(); //read current datas in db
let uid = req.body.id; // transfer "id" from TABLE to "uid"
/* Do actual updation of User via ID */
let dataup = db.get('users').find({ id: uid }).value();
if (dataup.First_Name === req.body.First_Name) {
console.log("No change in First_Name");
} else {
db.get('users').find({id: uid})
.assign({First_Name: req.body.First_Name})
.write();
}
if (dataup.Middle_Name === req.body.Middle_Name) {
console.log("No change in Middle_Name");
} else {
db.get('users').find({id: uid})
.assign({Middle_Name: req.body.Middle_Name})
.write();
}
if (dataup.Last_Name === req.body.Last_Name) {
console.log("No change in Last_Name");
} else {
db.get('users').find({id: uid})
.assign({Last_Name: req.body.Last_Name})
.write();
}
if (dataup.Email === req.body.Email) {
console.log("No change in Email");
} else {
db.get('users').find({id: uid})
.assign({Email: req.body.Email})
.write();
}
/* Do actual updation of User via ID ends here */
res.status(200);
res.redirect('/');
});

最佳答案

好吧,我的建议是添加一个函数来为您执行此操作,因为有很多重复。

if (dataup.Last_Name === req.body.Last_Name) {
console.log("No change in Last_Name");
} else {
db.get('users').find({id: uid})
.assign({Last_Name: req.body.Last_Name})
.write();
}

像这样:

function updateUser(userParam, userId, dbIntance, dataup){

if (dataup.userParam=== req.body.userParam) {
console.log(`No change in ${userParam}`);
} else {
dbIntance.get('users').find({id: userId})
.assign({userParam: req.body.userParam})
.write();
}
}

所以现在只需用这段代码替换所有的 if 即可。

const userDetail = ['First_Name ', 'Middle_Name', 'Last_Name', 'Email']

for(let i=0; i<userDetail.length; i++){
this.updateUser(userDetail[i], uid, db, dataup);
}

干净、简洁是我们的目标,而且也不仅仅是基本的。您可以查看下面的链接,了解 Nodejs 的基于 Controller 的结构,这是一些帮助您继续前进的高级内容。希望它有帮助:)

https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes

关于javascript - lowdb 添加/编辑/更新/删除成功,但需要使用 if/then/else 语句对更新部分进行一些更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59509480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com