javascript - Node.js Update Form for CRUD APP
问题描述
The form updates but only updates the first entry in my database. It does not update the entry of the specified id.
This is my schema:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDB');
var dbSchema = mongoose.Schema({
objID : String,
productName : String,
price : String,
quantity: Number
});
var Document = mongoose.model('Document', dbSchema);
The app.post Document.update is not creating the document on the specified id. When the information is posted through my form, the update takes place on the first db entry.
app.get('/update', function(req, res,) {
res.render('update', { title: 'Express' });
});
app.post('/updated/',
function(req, res) {
Document.update({
objID : req.body.id_name,
productName : req.body.product_name,
price : req.body.price_name,
quantity: req.body.quantity_name
}, function(err, obj) {
if (!err) {
res.redirect('/update');}
else {
res.send(err)
}
});
});
I have also tried these two methods.
app.post('/updated',
function(req, res) {
Document.findOneAndUpdate({objID: req.params.objID}, req.body, {new: true},
(err, obj) => {
if (!err) {
res.redirect('/update');
}
else {
res.send(err)
}
});
});
app.post('/updated/',
function (req,res) {
Document.findByIdAndUpdate(req.params.objID, {$set: req.body}, function (err, product) {
if (err) return next(err);
res.send('Product udpated.');
});
});
If anyone can just give the last nudge to assist me i would truly appreciate it.
And this is my update.pug file.
doctype html
head
meta(charset='utf-8')
meta(name='viewport' content='width=device-width, initial-scale=1.0')
title Superb Grocery IS
link(rel='stylesheet' type="text/css" href='stylesheets/style.css')
script(type='text/javascript' src='javascripts/validate.js')
.main-nav
ul.nav
li.name Superb Grocery IS
li
a(href='index') Home
li
a(href='listing') Listing
li
a(href='entry') Add
li
a(href='update') Update
li
a(href='delete') Delete
header
#wrapperr
h1(align='center' style='color:blueviolet') Update Products
form(name='form3' action='/updated' method='post' style='margin-top:
20px')
input(name='_method', value='PUT', type='hidden')
table#table2(align='center' border='3')
tr
td
label(for='entry_id') ID:
td
input#entry_id(type='text' name='id_name' pattern='^[a-zA-Z][a-zA-Z0-9-_\.]{5}$' placeholder='RWS35O' onblur='alphanumeric(this)' required='')
tr
td
label(for='entry_product') Product:
td
input#entry_product(type='text' name='product_name' onblur='letpattern(this)' required='')
tr
td
label(for='entry_price') Price:
td
input#entry_price(type='text' name='price_name' placeholder='9999 OR 9999.99' onblur='price(this)' required='')
tr
td
label(for='entry_quantity') Quantity:
td
input#entry_quantity(type='text' name='quantity_name' placeholder='9999' pattern='[0-9]' onblur='numeric(this)' required='')
tr
td(colspan='2' align='center')
button.reset(type='reset' value='Reset') Reset
button.update_btn(type='submit' value='Submit') Update
解决方案
const User = require('../models/user')
const jwt = require('../helpers/jwt')
module.exports = class {
static register(req, res, next) {
let user = {
name: req.body.name,
email: req.body.email,
password: req.body.password
}
User.create(user)
.then(result => {
res.status(201).json(result)
})
.catch(err => {
next(err)
})
}
static login(req, res, next) {
let user = {
email: req.body.email,
password: req.body.password
}
// console.log(user);
User.findOne(user)
.then(userLogin => {
let token = jwt.generateToken({
email: userLogin.email,
id: userLogin._id
})
res.status(200).json({ token: token })
})
.catch(err => {
;(err.statusCode = 400), (err.message = 'Email or Password is invalid')
next(err)
})
}
static getUser(req, res, next) {
try {
let user = {
_id: req.body.user._id,
name: req.body.user.name,
email: req.body.user.email,
imageUrl: req.body.user.imageUrl,
role: req.body.user.role,
balance: req.body.user.balance
}
res.status(200).json(user)
} catch (err) {
next(err)
}
}
static logout(req, res, next) {
res.status(200).json({
message: 'Successfully logout',
accountType: req.body.user.accountType
})
}
}
==== router index ====
const express = require('express')
const router = express.Router()
// router.get('/', )
router.use('/users', require('./users'))
router.use('/products', require('./product'))
router.use('/transactions', require('./transaction'))
module.exports = router
==== router user ====
const express = require('express')
const router = express.Router()
const User = require('../controllers/userController')
const auth = require('../middlewares/auth')
/* GET users listing. */
router.post('/register', User.register)
router.post('/login', User.login)
router.get('/', auth.authentication, User.getUser)
router.post('/logout', auth.authentication, User.logout)
module.exports = router
===env===
jwt_key, port, db_uri
推荐阅读
- amazon-web-services - 从 Kinesis 数据流到 Kinesis Firehose 到 S3 存储桶的 CloudFront 实时日志
- node.js - 尝试在 node.js 中制作一个简单的命令行习惯跟踪器,在更新和存储数据时遇到问题
- node.js - 使用 npm、npm install x --save 或 npm install --save x 安装软件包?
- html - 使用asp.net向表中添加数据
- java - 错误:JRE/JDK 版本和类文件版本之间的差异
- javascript - 获取此滑块以自动播放
- python - np.exp 的点积问题
- c++ - CPP中没有明显原因的奇怪输出
- android - Basic Jetpack Compose Codelab 的“找不到具有此名称的参数:items”
- java - Spring Boot 连接到 Java 中的 MySQL 错误