You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js调用MongoDB获取数据异常:getdata方法无法按ID查询资源

问题:GET API无法通过ID查询数据,返回错误

调用/getdata接口时,无法通过ID定位数据库中的资源,代码进入try块但查询不到数据,最终执行catch返回not find错误。

原index.js代码

const connectToMongo = require('./db');
var cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const photo = require('./models/photoModel');
const formidable = require('formidable');
const fs = require('fs');
const photoModel = require('./models/photoModel');

connectToMongo();
const app = express();
app.use(cors());
const port = 5000;

//app.use(express.json());
app.use(bodyParser.json());

const userData = (req, res) => {
  const form = new formidable.IncomingForm();
  console.log('1');
  form.parse(req, (err, fields, file) => {
    console.log('2');
    if (fields) {
      console.log('3');
      const { email, mno, name } = fields;
      if (!email || !mno || !name) {
        console.log('4');
        return res.status(400).json({
          error: 'Fill all the fields',
        });
      }
    }
    if (file.photo) {
      if (file.photo.size > 4000000) {
        return res.status(400).json({
          error: 'image size is too long',
        });
      }
      const user = new photo(fields);
      user.photo.data = fs.readFileSync(file.photo.filepath);
      user.photo.contentType = file.photo.type;

      user.save((err, user) => {
        if (err) {
          return res.status(400).json({
            error: 'Not save in db',
          });
        }
        console.log('above json');
        res.json(user);
      });
    }
  });
};

// The issue is here
const getdata = async (req, res) => {
  try {
    console.log('yes');
    const photo = await photo.find({ photo: req.photo.id });
    res.json(photo);
  } catch (error) {
    return res.status(400).json({
      error: 'not find',
    });
  }
};

//router
app.post('/userdashboard', userData);
app.get('/getdata', getdata);

app.listen(port, () => {
  console.log(`Dashboard Backend listening on port ${port}`);
});

模型schema代码

const mongoose = require('mongoose');
const { Schema } = mongoose;
const PhotoSchema = new Schema({
    name:{
        type:String,
        trim:true,
        required:true
    },
    email:{
        type:String,
        trim:true,
        required:true
    },
    photo:{
        data:Buffer,
        contentType:String
    },
    mno:{
        type:Number,
        required:true
    }

  });

  module.exports=mongoose.model('photo',PhotoSchema);

问题原因及修复方案

核心问题点:

  • 查询条件完全错误:
    1. req.photo.id不存在,GET请求不会自动携带photo对象,需要通过URL参数从req.params.id获取要查询的ID。
    2. photo是Schema中存储图片数据的字段,不是文档的主键,MongoDB默认用_id作为文档唯一标识,查询ID应使用_id。
  • 变量名冲突:const photo = await photo.find(...)中,photo同时作为模型名和查询结果变量,会覆盖模型引用,引发错误。
  • 路由未接收ID参数:当前/getdata路由没有定义ID参数,无法传递要查询的资源ID。

修复后的代码:

// 修复后的getdata函数
const getdata = async (req, res) => {
  try {
    console.log('yes');
    // 使用req.params.id获取URL中的ID,用findById简化主键查询,变量名避免冲突
    const foundPhoto = await photo.findById(req.params.id);
    if (!foundPhoto) {
      return res.status(404).json({ error: '资源不存在' });
    }
    res.json(foundPhoto);
  } catch (error) {
    console.error(error); // 打印错误详情便于调试
    return res.status(400).json({ error: '查询失败' });
  }
};

// 修改路由,添加ID参数
app.get('/getdata/:id', getdata);

额外优化建议:

  • 打印错误日志便于排查问题(比如ID格式错误、数据库连接异常等)。
  • 区分资源不存在(404)和查询错误(400)的状态码,符合REST规范。
  • 统一模型导入命名,避免重复导入导致的混淆,比如只保留const photoModel = require('./models/photoModel');。

内容的提问来源于stack exchange,提问作者Mirza M Azeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 03:50:34