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

MongooseError:Model.findOne()不再接受回调函数 MERN新手求助

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

这个错误的核心原因是Mongoose 6.x及以上版本彻底移除了对查询方法回调参数的支持,所有CRUD方法(包括你代码里的find())现在默认返回Promise,不能再像旧版本那样直接传入回调函数。

方案1:使用Async/Await(推荐写法)

将路由处理函数改为异步函数,通过try/catch捕获错误,代码结构更直观易读:

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://user123:<password>@cluster0.16wokcq.mongodb.net/merntutorial?retryWrites=true&w=majority"
)
.then(() => console.log("数据库连接成功"))
.catch(err => console.error("数据库连接失败:", err));

// 改用async/await处理查询逻辑
app.get("/getUsers", async (req, res) => {
  try {
    const result = await UserModel.find({});
    res.json(result);
  } catch (err) {
    res.status(500).json(err);
  }
});

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

方案2:使用Promise链式调用

如果更习惯Promise的链式写法,可以用.then()和.catch()替代回调:

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

额外提示

  • 不建议降级Mongoose版本来兼容旧写法,新版本在性能、安全性上有更多优化。
  • 数据库连接务必添加状态处理,避免连接失败时无任何提示信息。

内容的提问来源于stack exchange,提问作者Fyılmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 22:30:16