首页 > 解决方案 > mongoose 通过 mongo atlas TypeError:无法读取未定义的属性“长度”

问题描述

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

这是导致问题的获取代码片段

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

标签: javascriptnode.jsmongodbmongoosemongodb-atlas

解决方案


错误的根本原因是您声明的架构根本不是真正的架构。您需要将其声明为猫鼬模式,因此而不是

const itemsSchema = {
    name: String
};

你应该做:

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

参考:mongoose.js 文档


推荐阅读