Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

283
Views
Cannot read properties of undefined (reading 'length') in nodejs
const cities = require('./cities');
const { places, descriptor } = require('./seedHelpers');
const Campground = require('../models/campground');
const { length } = require('./cities');

mongoose.connect('mongodb://localhost:27017/starwar-camp', {
    // useNewUrlParser: true,
    // useCreateIndex: true,
    // useUnifiedTopology: true
});

const db = mongoose.connection;
db.on("error", console.error.bind(console, "Connection error:"));
db.once("open", () => {
    console.log("Database connected Successfully!");
});

const sample = array => array[Math.floor(Math.random() * array.length)];

const seedDB = async() => {
    await Campground.deleteMany({});
    for (let i = 0; i < 50; i++) {
        const random1000 = Math.floor(Math.random() * 1000);
        const camp = new Campground({
            location: `${cities[random1000].city}, ${cities[random1000].state}`,
            title: `${sample(descriptor)} ${sample(places)}`
        })
        await camp.save();
    }
}

seedDB().then(() => {
    mongoose.connection.close();
})

This is what error I am getting

const sample = array => array[Math.floor(Math.random() * array.length)];
                                                               ^

TypeError: Cannot read properties of undefined (reading 'length')
    at sample (E:\EDI\YelpCamp\seeds\index.js:19:64)
    at seedDB (E:\EDI\YelpCamp\seeds\index.js:27:23)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

I am actually doing a project from udemy and I have written the same code as from the video and his code get executed without any error but not mine.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Its because either one or all of the descriptor or places is returning null or undefined from line

const { places, descriptor } = require('./seedHelpers');

try to console these two values separately to see if they give anything

from your codes above it seems that the sample function

const sample = array => array[Math.floor(Math.random() * array.length)];

works just fine and its role is to give you random sample from the array of samples

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!