Home > Blockchain >  Getting this error when adding a product to mongoDB
Getting this error when adding a product to mongoDB

Time:11-19

This is the file containing the Schema

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

const productSchema = new Schema({
    _id: {
        type: Number,
        required: true
    },
    product_name: {
        type: String,
        required: true
    },
    price: {
        type: String,
        required: true
    },
    quantity: {
        type: Number,
        required: true
    },
    product_collection: {
        type: String,
        required: true,
        enum: ['Nike' , 'Addidas']
    },
    product_image_url: {
        type: String,
        required: true
    },
    product_type: [
        {
            color: {
                type: String,
                required: true,
            }
        },
        {
            size: {
                type: Number,
                required: true,
                enum: ['40', '41' , '42']
            }
        }
    ]
})

const Product = mongoose.model('Product' , productSchema);

module.exports = Product;

This is the seeds file where i want to create a product

//Require Models
const mongoose = require('mongoose');

//Require Models
const Product = require('./models/product');

//Connecting to DB server
mongoose.connect('mongodb://localhost:27017/ecom', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
})
    .then(() => {
        console.log('DATABASE CONNECTED')
    })
    .catch(err => {
        console.log('SOMETHING WENT WRONG WITH MONGO')
        console.log(err)
    })

    const p = new Product({
        _id: 1,
        product_name: 'Nike HyperVenom',
        price: 150,
        quantity: 30,
        product_collection: 'Nike',
        product_image_url: 'zzzzz',
        product_type: [
            {
                color: 'red'
            },
            {
                size: [41 , 42]
            }
        ]
    })

    p.save().then(p => {
        console.log(p)
    })
    .catch(e => {
        console.log(e)
    })

This is the error that is displayed in console.

Error: Product validation failed: product_type.1.color: Path `color` is required

 errors: {
    'product_type.1.color': ValidatorError: Path `color` is required.
        at validate (C:\Users\hadiz\Desktop\Business\portfolioprojects\ecommerce
\node_modules\mongoose\lib\schematype.js:1277:13)
        at C:\Users\hadiz\Desktop\Business\portfolioprojects\ecommerce\node_modu
les\mongoose\lib\schematype.js:1260:7
        at Array.forEach (<anonymous>)
        at SchemaString.SchemaType.doValidate (C:\Users\hadiz\Desktop\Business\p
ortfolioprojects\ecommerce\node_modules\mongoose\lib\schematype.js:1210:14)
        at C:\Users\hadiz\Desktop\Business\portfolioprojects\ecommerce\node_modu
les\mongoose\lib\document.js:2690:18
        at processTicksAndRejections (node:internal/process/task_queues:76:11) {
      properties: [Object],
      kind: 'required',
      path: 'color',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'Product validation failed'
}

Any idea how to fix this , I am a bit of a beginner in mongoose and mongoDB. I think the problem is with the product_type section , am i giving them a value in the right way in the seeds file ?

CodePudding user response:

The product_type object in your schema indicates that every object inside it must have a color key-value pair. The error was about your second object in product_type (index 1) does not have the color key. You should change product_type from an array to an object. I.E.

product_type: {
    color: {
        type: String,
        required: true,
    },
    size: [{
        type: Number,
        required: true,
        enum: [40, 41, 42]
    }],
}

And your input should become:

product_type: {
    color: "red",
    size: [41, 42],
}
  • Related