Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

287
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda