【问题标题】:mongoose through mongo atlas TypeError: Cannot read property 'length' of undefinedmongoose 通过 mongo atlas TypeError:无法读取未定义的属性“长度”
【发布时间】:2021-04-30 07:17:30
【问题描述】:

我正在使用 mongoose,在从本地 mongodb 服务器 (mongod) 移动到 mongodb atlas cloud 后遇到了这个问题:TypeError: Cannot read property 'length' of undefined

这是导致问题的获取代码的 sn-p

app.get('/', function(req, res) {
Item.find({}, function(err, results) {
    //Item is a mongoose model
    if (results.length === 0) {
        item.save();
        res.redirect("/");
    } else {
        res.render('toDoLists', { Title: title, addedItems: results });
        //using ejs
    }

});

});

这是 github 中的全部代码:

https://github.com/oubaydos/toDoList-webDevLearningPath/blob/main/app.js

【问题讨论】:

  • 在任何操作之前检查错误console.log(err)
  • @turivishal 我试过了,它没有提供太多信息:在函数实例上发出“错误”事件:在 C:\Users**\node_modules\mongoose\lib\model.js:4888 :13 在 C:\Users**\node_modules\mongoose\lib\helpers\promiseOrCallback.js:16:11 [... 匹配原始堆栈跟踪的行 ...] 在 processTimers (internal/timers.js:492:7 )
  • 可能是连接问题,你要检查你的连接。 TypeError 告诉您 response 未定义。
  • @ISAE 我不认为这是连接问题,如果我使用 mongo 命令(客户端控制台)而不是 mongoose,一切都可以正常工作。问题在我移至 mongodb atlas 后开始出现,似乎interpeter 无法创建项目模型。如果你检查了 github 中的代码,并告诉我你的想法,那就太好了!
  • 在您的 app.js 中乍一看,mongoose.connect 指向您的本地主机,而不是任何 atlas 连接

标签: javascript node.js mongodb mongoose mongodb-atlas


【解决方案1】:

错误的根本原因是您声明的架构根本不是真正的架构。 您需要将其声明为 mongoose 模式,所以不是

const itemsSchema = {
    name: String
};

你应该这样做:

const itemSchema = new mongoose.Schema({
    name: String
});

参考:mongoose.js docs

【讨论】:

    【解决方案2】:

    感谢 ISAE,我发现问题出在与 mongodb atlas 数据库的连接上,而我与 localhost 建立了连接。

    【讨论】:

      猜你喜欢
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2020-07-20
      • 2020-03-07
      • 1970-01-01
      相关资源
      最近更新 更多