简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM