node.js - 无法使用 Express 从 MongoDB 中使用 ID 检索数据
问题描述
我使用 NodeJS、Express 和 MongoDB 创建了一个 rest API。我可以使用 MongoDB Compass 成功创建数据并在数据库中查看它们,但无法使用生成的 Id 获取单个数据。每当我尝试时,它都会给我一个 404 错误。
这是我的代码:
bootcamps.js(控制器)
const Bootcamp = require('../models/Bootcamp') exports.getBootcamps = async (req, res, next) => { try { const bootcamps = await Bootcamp.find() res.status(200).json({success: true, count: bootcamps.length, data: bootcamps}) } catch (error) { res.status(400).json({success: false}) } } exports.getBootcamp = async (req, res, next) => { try { const bootcamp = await Bootcamp.findById({_id: req.params.id}) if (!bootcamp) { return res.status(400).json({success: false}) } res.status(200).json({success: true, data: bootcamp}) } catch (error) { res.status(400).json({success: false}) } } exports.createBootcamps = async (req, res, next) => { try { const bootcamp = await Bootcamp.create(req.body) res.status(201).json({ success: true, data: bootcamp, msg: 'Bootcamp created' }) } catch (error) { console.log(error) res.status(400).json({success: false}) } } exports.updateBootcamp = async (req, res, next) => { try { const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }); if (!bootcamp) { return res.statuc(400).json({success: false}) } res.status(200).json({ success: true, data: bootcamp }) } catch (error) { return res.statuc(400).json({success: false}) } } exports.deleteBootcamp = async (req, res, next) => { try { const bootcamp = await Bootcamp.findByIdAndDelete(req.params.id); if (!bootcamp) { return res.statuc(400).json({success: false}) } res.status(200).json({ success: true, data: {} }) } catch (error) { return res.statuc(400).json({success: false}) } }
Bootcamp.js(模型)
const mongoose = require('mongoose') const BootcampSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Please add a name'], unique: true, trim: true, maxlength: [50, 'Name can not be more than 50 characters'] }, slug: String, description: { type: String, required: [true, 'Please add a description'], maxlength: [500, 'Name can not be more than 50 characters'] }, website: { type: String, match: [ /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/, "Please use a valid URL with HTTP or HTTPS" ] }, phone: { type: String, maxlength: [20, 'Phone number can not be longer than 20 characters'] }, email: { type: String, match: [ /^\w+([\.-]?\w+)+@\w+([\.:]?\w+)+(\.[a-zA-Z0-9]{2,3})+$/, 'Please add a valid email address' ] }, address: { type: String, required: [true, 'Please add an address'] }, location: { type: { type: String, enum: ['Point'], required: false }, coordinates: { type: [Number], required: false, index: '2dsphere' } }, formattedAddress: String, street: String, city: String, state: String, zipcode: String, country: String, careers: { type: [String], required: true, enum: [ 'Web Development', 'Mobile Development', 'UI/UX', 'Data Science', 'Business', 'Other' ] }, averageRating: { type: Number, min: [1, 'Rating must be at least 1'], max: [10, 'Rating can not be more than 10'] }, averageCost: Number, photo: { type: String, default: 'no-photo.jpg' }, housing: { type: Boolean, default: false }, jobAssistance: { type: Boolean, default: false }, jobGuarantee: { type: Boolean, default: false }, acceptGi: { type: Boolean, default: false }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model('Bootcamp', BootcampSchema)
bootcamps.js(路线)
const express = require('express') const { getBootcamp, getBootcamps, createBootcamps, updateBootcamp, deleteBootcamp } = require('../controllers/bootcamps') const router = express.Router() router.route('/').get(getBootcamps).post(createBootcamps) router.route(':id').put(updateBootcamp).delete(deleteBootcamp).get(getBootcamp) module.exports = router
index.js(入口文件)
const express = require('express') const dotenv = require('dotenv') const morgan = require('morgan') const connectDB = require('./config/db') const colors = require('colors') dotenv.config({ path: './config/config.env' }) connectDB() const bootcamps = require('./routes/bootcamps') const app = express(); app.use(express.json()) if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')) } app.use('/api/v1/bootcamps', bootcamps) const PORT = process.env.PORT || 5000 const server = app.listen(PORT, console.log(`Server is running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold)) process.on(`unhandledRejection`, (err, promise) => { console.log(`Error: ${err.message}`.red) server.close(() => process.exit(1)) })
解决方案
发现错误!
我忘了在单条路线上添加“/”
前:
router.route(':id').put(updateBootcamp).delete(deleteBootcamp).get(getBootcamp)
后:
router.route('/:id').put(updateBootcamp).delete(deleteBootcamp).get(getBootcamp)
令人惊讶的是,控制台和邮递员的结果并没有抱怨并指出这一点!
推荐阅读
- reactjs - 在渲染道具中调用的 setState 导致反应警告
- python - 无法使用自定义服务方法保存 tf.keras.Model
- python - 如何在预测阶段获得所有输出 keras 层(特征图)?
- ios - 从 android studio 在 iOS 上运行 Flutter 应用程序
- python - 为什么我们不能在 Python 中下标“int”对象
- ruby-on-rails - 当方法不存在时,如何使用 rspec 导致测试失败?
- gnuradio - 什么是
gnuradio 3.7 XML 中的属性意味着什么,它在 3.8 YML 中的等价物是什么? - javascript - 创建喜欢不喜欢的功能喜欢instagram
- c++ - 我可以使用没有 dso 问题的库进行编译吗?
- node.js - 自动重新发送图像