【问题标题】:Mongoose .find() method causes requests to hangMongoose .find() 方法导致请求挂起
【发布时间】:2025-12-09 21:35:01
【问题描述】:

我已经定义了这条路线,但是对它的任何请求都会停留在“待处理”状态并永远运行。

当我记录代码时,我看到 1 后跟 4,这意味着 find 方法中的代码永远不会被执行

  # Calendar routes
  router.get '/calendars', (req, res) ->
    console.log '1'
    Calendar.find (err, calendars) ->
      console.log "2" + err
      console.log "3" + calendars
      res.send(err) if err
      res.json(calendars)
      return
    console.log '4'
    return

型号

mongoose = require("mongoose")

module.exports = mongoose.model("Calendar",
  name: String
)

关于为什么会这样的任何想法?

【问题讨论】:

  • 当未调用 Mongoose 回调时,通常是因为该模型的连接未打开。您的mongoose.connect 通话成功了吗?
  • 我如何检查这个?
  • 为您的mongoose.connect 调用提供回调函数参数。
  • 我不会在任何地方明确调用 mongoose.connect

标签: node.js express mongoose


【解决方案1】:

在您致电 mongoose.connect 之前,您的 mongoose 查询只会排队。

在你的启动代码中添加这样的代码来连接:

mongoose.connect('mongodb://localhost/test', function(err) {
    if (err) {
        console.err(err);
    } else {
        console.log('Connected');
    }    
});

在连接字符串中,将test 替换为您的数据库名称。

【讨论】:

    最近更新 更多