如何对 mongodb 数据库执行更新方法?
我有我的更新按钮,它执行 get 请求以获取带有 id 的数据并填充插槽。然后,使用下面的表单执行另一个获取请求来发送更新数据的请求。
<form action="//updateBookRequest" method="GET" id="update-book">
<!-- Book Name -->
<div class="form-group">
<label for="name">Name</label>
<input type="hidden" name="id" value="<%= book._id %> ">
<input type="text" name="name" value="<%= book.name %> " placeholder="The Alchemist">
</div>
<!-- Author Name -->
<div class="form-group">
<label for="author">Author</label>
<input type="text" name="author" value="<%= book.author %> " placeholder="Paulo Coelho">
</div>
<!-- Language -->
<div class="form-group">
<label for="language">Language</label>
<input type="text" name="language" value="<%= book.language %> " placeholder="English">
</div>
<!-- Date -->
<div class="form-group">
<label for="date">Date</label>
<input type="date" name="date" value="<%= book.date %> " placeholder="">
</div>
<div class="form-group">
<div class="buttons">
<button class="btn">Cancel</button>
<button class="btn" type="submit">Save</button>
</div>
</div>
</form>
路线如下所示:
route.get('/update-book', services.updateBook)
services.updateBook 如下所示:
exports.updateBook = (req, res) => {
axios.put(`http://localhost:5000/api/books/${req.query.id}`)
.then(function(response) {
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
但由于某种原因,它不更新数据。
当我在邮递员中执行此操作时,使用相同的“http://localhost:5000/api/books/id”,它工作得很好,并按应有的方式使用邮递员主体更新数据。
但是,当我尝试在 ejs 文件中使用以下部分执行此操作时,情况并非如此。
我似乎找不到问题出在哪里。其他功能(例如添加新数据、使用 ID 删除数据、显示所有数据)似乎工作正常。
我怎样才能让它更新数据?
这是 server.js 文件:
const express = require('express')
const dotenv = require('dotenv')
const bodyparser = require('body-parser')
const path = require('path')
const connnectDB = require('./server/database/connection')
const app = express()
dotenv.config({path:'config.env'})
const port = process.env.port || 5050
connnectDB()
app.use(bodyparser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.use('/css', express.static(path.resolve(__dirname, 'assets/css')))
app.use('/js', express.static(path.resolve(__dirname, 'assets/js')))
app.use('/', require('./server/routes/router'))
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
这是 server/controller/controller.js
const Userdb = require('../model/model')
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({message: 'content can not be empty'})
return
}
const user = new Userdb({
name: req.body.name,
author: req.body.author,
language: req.body.language,
date: req.body.date,
description: req.body.description
})
user
.save(user)
.then(data => {
// res.send(data)
res.redirect('/')
})
.catch(err => {
res.status(500).send({
message: err.message || 'some error occured'
})
})
}
exports.find = (req, res) => {
if (req.query.id) {
const id = req.query.id
Userdb.findById(id)
.then(data => {
if (!data) {
res.status(404).send({message: `error ${id}`})
} else {
res.send(data)
}
})
.catch(err => {
res.status(500).send({message: `error ${id}`})
})
} else {
Userdb.find()
.then(user => {
res.send(user)
})
.catch(err => {
res.status(500).send({message:err.message || 'error while finding data'})
})
}
}
exports.update = (req, res) => {
if (!req.body) {
return res.status(400).send({message: 'Data to update is empty'})
}
const id = req.params.id
Userdb.findByIdAndUpdate(id, req.body, {useFindAndModify: false})
.then(data => {
if (!data) {
res.status(404).send({message: `can't update ${id}`})
} else {
res.send(data)
}
})
.catch(err => {
res.status(500).send({message: 'err'})
})
}
exports.delete = (req, res) => {
const id = req.params.id
Userdb.findByIdAndDelete(id)
.then(data => {
if (!data) {
res.status(404).send({message: `${id} is wrong`})
} else {
res.send({message: 'user deleted'})
}
})
.catch(err => {
res.status(500).send({message: `could not delete with ${id}`})
})
}
这是 server/routes/router.js
const route = express.Router()
const services = require('../services/render')
const controller = require('../controller/controller')
route.get('/', services.homeRoute)
route.get('/add-book', services.addNewBook)
route.get('/update-book', services.updateBook)
route.get('/updateBookRequest', services.updateBookRequest)
route.get('/delete-book', services.deleteBook)
// API
route.post('/api/books', controller.create)
route.get('/api/books', controller.find)
route.put('/api/books/:id', controller.update)
route.delete('/api/books/:id', controller.delete)
module.exports = route
这是 server/services/render.js
const axios = require('axios')
exports.homeRoute = (req, res) => {
axios.get('http://localhost:5000/api/books')
.then(function(response) {
res.render('index', {books: response.data})
})
.catch(err => {
res.send(err)
})
}
exports.addNewBook = (req, res) => {
res.render('add_new_book')
}
exports.updateBook = (req, res) => {
axios.get('http://localhost:5000/api/books', {params:{id:req.query.id}})
.then(function(userdata) {
res.render('update_book', {book:userdata.data})
})
.catch(err => {
res.send(err)
})
}
exports.updateBookRequest = (req, res) => {
console.log(req)
axios.put(`http://localhost:5000/api/books/${req.query.id}`, {book:req.body})
.then(function(response) {
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
exports.deleteBook = (req, res) => {
axios.delete(`http://localhost:5000/api/books/${req.query.id}`)
.then(function(response) {
console.log('deleted')
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
这是到目前为止的整个代码
I have my update button that performs a get request to fetch the data with the id and fills the slots. Then, using the form below I perform another get request to send a request to update the data.
<form action="//updateBookRequest" method="GET" id="update-book">
<!-- Book Name -->
<div class="form-group">
<label for="name">Name</label>
<input type="hidden" name="id" value="<%= book._id %> ">
<input type="text" name="name" value="<%= book.name %> " placeholder="The Alchemist">
</div>
<!-- Author Name -->
<div class="form-group">
<label for="author">Author</label>
<input type="text" name="author" value="<%= book.author %> " placeholder="Paulo Coelho">
</div>
<!-- Language -->
<div class="form-group">
<label for="language">Language</label>
<input type="text" name="language" value="<%= book.language %> " placeholder="English">
</div>
<!-- Date -->
<div class="form-group">
<label for="date">Date</label>
<input type="date" name="date" value="<%= book.date %> " placeholder="">
</div>
<div class="form-group">
<div class="buttons">
<button class="btn">Cancel</button>
<button class="btn" type="submit">Save</button>
</div>
</div>
</form>
The route looks like this:
route.get('/update-book', services.updateBook)
And the services.updateBook looks like this:
exports.updateBook = (req, res) => {
axios.put(`http://localhost:5000/api/books/${req.query.id}`)
.then(function(response) {
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
But for some reason, it doesn't update the data.
When I do it in the postman, using the same 'http://localhost:5000/api/books/id', it works just fine and update the data with the postman body as it should.
But, it doesn't when I try to do it in the ejs file with the following section.
I can't seem to find where the problem is. Other functionalities such as adding new data, deleting the data using the id, displaying all the data seem to work fine.
How can I make it to update the data?
This is server.js file:
const express = require('express')
const dotenv = require('dotenv')
const bodyparser = require('body-parser')
const path = require('path')
const connnectDB = require('./server/database/connection')
const app = express()
dotenv.config({path:'config.env'})
const port = process.env.port || 5050
connnectDB()
app.use(bodyparser.urlencoded({extended:true}))
app.set('view engine', 'ejs')
app.use('/css', express.static(path.resolve(__dirname, 'assets/css')))
app.use('/js', express.static(path.resolve(__dirname, 'assets/js')))
app.use('/', require('./server/routes/router'))
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
This is the server/controller/controller.js
const Userdb = require('../model/model')
exports.create = (req, res) => {
if (!req.body) {
res.status(400).send({message: 'content can not be empty'})
return
}
const user = new Userdb({
name: req.body.name,
author: req.body.author,
language: req.body.language,
date: req.body.date,
description: req.body.description
})
user
.save(user)
.then(data => {
// res.send(data)
res.redirect('/')
})
.catch(err => {
res.status(500).send({
message: err.message || 'some error occured'
})
})
}
exports.find = (req, res) => {
if (req.query.id) {
const id = req.query.id
Userdb.findById(id)
.then(data => {
if (!data) {
res.status(404).send({message: `error ${id}`})
} else {
res.send(data)
}
})
.catch(err => {
res.status(500).send({message: `error ${id}`})
})
} else {
Userdb.find()
.then(user => {
res.send(user)
})
.catch(err => {
res.status(500).send({message:err.message || 'error while finding data'})
})
}
}
exports.update = (req, res) => {
if (!req.body) {
return res.status(400).send({message: 'Data to update is empty'})
}
const id = req.params.id
Userdb.findByIdAndUpdate(id, req.body, {useFindAndModify: false})
.then(data => {
if (!data) {
res.status(404).send({message: `can't update ${id}`})
} else {
res.send(data)
}
})
.catch(err => {
res.status(500).send({message: 'err'})
})
}
exports.delete = (req, res) => {
const id = req.params.id
Userdb.findByIdAndDelete(id)
.then(data => {
if (!data) {
res.status(404).send({message: `${id} is wrong`})
} else {
res.send({message: 'user deleted'})
}
})
.catch(err => {
res.status(500).send({message: `could not delete with ${id}`})
})
}
This is server/routes/router.js
const route = express.Router()
const services = require('../services/render')
const controller = require('../controller/controller')
route.get('/', services.homeRoute)
route.get('/add-book', services.addNewBook)
route.get('/update-book', services.updateBook)
route.get('/updateBookRequest', services.updateBookRequest)
route.get('/delete-book', services.deleteBook)
// API
route.post('/api/books', controller.create)
route.get('/api/books', controller.find)
route.put('/api/books/:id', controller.update)
route.delete('/api/books/:id', controller.delete)
module.exports = route
This is server/services/render.js
const axios = require('axios')
exports.homeRoute = (req, res) => {
axios.get('http://localhost:5000/api/books')
.then(function(response) {
res.render('index', {books: response.data})
})
.catch(err => {
res.send(err)
})
}
exports.addNewBook = (req, res) => {
res.render('add_new_book')
}
exports.updateBook = (req, res) => {
axios.get('http://localhost:5000/api/books', {params:{id:req.query.id}})
.then(function(userdata) {
res.render('update_book', {book:userdata.data})
})
.catch(err => {
res.send(err)
})
}
exports.updateBookRequest = (req, res) => {
console.log(req)
axios.put(`http://localhost:5000/api/books/${req.query.id}`, {book:req.body})
.then(function(response) {
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
exports.deleteBook = (req, res) => {
axios.delete(`http://localhost:5000/api/books/${req.query.id}`)
.then(function(response) {
console.log('deleted')
res.redirect('/')
})
.catch(err => {
res.send(err)
})
}
This is by far the whole code
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在更新函数中使用回调。您也可以使用 {new: true} 来获取更新的文档。
还要确保您的 req.body 是一个对象。如果您不确定,请检查控制台日志中的 req.body
You need to use a callback in your update function. Also you can use {new: true} to get the updated document.
Also make sure your req.body is an object. if you are unsure, check req.body in console log