Diskusi Muhammad Ihsan

Selesai
Muhammad Ihsan
Ditanyakan pada: Relasi Data One To Many

TypeError: Cannot read properties of undefined (reading 'push')

TypeError: Cannot read properties of undefined (reading 'push')

const mongoose = require('mongoose');

// connect to mongodb
mongoose.connect('mongodb://127.0.0.1/relation_db')
    .then((result) => {
        console.log('connected to mongodb')
    }).catch((err) => {
        console.log(err)
    });

const farmSchema = new mongoose.Schema({
    name: String,
    city: String,
})

const productSchema = new mongoose.Schema({
    name: String,
    price: Number,
    season: {
        type: String,
        enum: ['Spring', 'Summer', 'Auntum', 'Winter']
    },
    products: [{
        type: mongoose.Schema.Types.ObjectId, // kumpulan id id dari mongo nya sendiri
        ref : 'Product' // untuk mengambil data document/collection dari ObjectId
    }]
})

const Product = mongoose.model('Product', productSchema)
const Farm = mongoose.model('Farm', farmSchema)

const makeFarm = async () => {
    const farm = new Farm({
        name: 'Farm',
        city : 'Serpong',
    })

    const pisang = await Product.findOne({name: 'Pisang'})
    farm.products.push(pisang)
    await farm.save()
    console.log(farm)
}

makeFarm();

Output : TypeError: Cannot read properties of undefined (reading 'push')

Kira kira saya salah dimana ya? terima kasih :)

1 Jawaban

Avatar
BroKoding

7 bulan yang lalu

Jawaban Terpilih

Halo kak, dari pesan error yang didapat menandakan tidak ada object products pada object farm. Terlihat dari definisi object farm tidak diberikan properti products.

Berikut contoh modifikasi :

const farm = new Farm({
        name: 'Farm',
        city : 'Serpong',
    products: []
    })