繁体   English   中英

无法使用 Express 从 MongoDB 检索使用 ID 的数据

[英]Unable to retrieve the data using ID from MongoDB using Express

我已经使用 NodeJS、Express 和 MongoDB 创建了一个 rest API。 我可以使用 MongoDB Compass 成功创建数据并在数据库中查看它们,但无法使用生成的 Id 获取单个数据。 每当我尝试时,它都会给我一个 404 错误。

这是我的代码:

  1. 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}) } }
  2. 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)
  3. 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
  4. 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)

令人惊讶的是,控制台和邮递员的结果并没有抱怨并指出这一点!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM