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

MongooseError排查:Model.find()不再接受回调函数

解决MongooseError: Model.find() no longer accepts a callback错误

你遇到的500内部服务器错误,核心原因是新版Mongoose(v6及以上版本)已完全移除对回调函数的支持,Model.find()方法现在仅返回Promise对象,不再接受回调参数作为输入。

修复方案

将/getUsers接口的回调写法改为async/await语法(和你已有的/createUser接口风格统一,代码更简洁易读),或者使用Promise链式调用。

修改后的完整代码

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const UserModel = require("./models/Users");

const cors = require("cors");

app.use(express.json());
app.use(cors());

mongoose.connect(
  "mongodb+srv://User:<password>@cluster0.o6pjbpq.mongodb.net/Database?retryWrites=true&w=majority" //此部分已检查无问题
);

// 使用async/await重构getUsers接口
app.get("/getUsers", async (req, res) => {
  try {
    const result = await UserModel.find({});
    res.json(result);
  } catch (err) {
    res.status(500).json(err);
  }
});

app.post("/createUser", async (req, res) => {
  const user = req.body;
  const newUser = new UserModel(user);
  await newUser.save();

  res.json(user);
});

app.listen(3000, () => {
  console.log("SERVER RUNS PERFECTLY!");
});

可选:Promise链式调用写法

如果你更习惯Promise风格,也可以这样写:

app.get("/getUsers", (req, res) => {
  UserModel.find({})
    .then(result => res.json(result))
    .catch(err => res.status(500).json(err));
});

额外说明

  • 加入try/catch或.catch()可以捕获数据库查询中的异常,并返回标准的500错误状态码,更符合HTTP错误规范
  • Mongoose v6+开始所有CRUD方法都只返回Promise,这是官方推进异步代码标准化的举措,建议统一使用async/await语法维护代码一致性

内容的提问来源于stack exchange,提问作者PicasoTheDealer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:52:52