oubaydos
oubaydos

Reputation: 192

mongoose through mongo atlas TypeError: Cannot read property 'length' of undefined

i am using mongoose and i encountered this problem after moving from the local mongodb server (mongod) to mongodb atlas cloud : TypeError: Cannot read property 'length' of undefined

here's a snippet of the get code causing the problem

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
    }

});

});

here's the whole code in github :

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

Upvotes: 1

Views: 2587

Answers (2)

oubaydos
oubaydos

Reputation: 192

thanks to ISAE i found that the problem was in the connection with the mongodb atlas database, i had a connection with the localhost instead.

Upvotes: 1

ISAE
ISAE

Reputation: 538

The underlying cause for the error is that your declared schema isn't really a schema at all. You need to declare it as a mongoose schema, so instead of

const itemsSchema = {
    name: String
};

You should do:

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

reference: mongoose.js docs

Upvotes: 1

Related Questions