Home > Net >  Mongoose ValidationError: Product validation failed: CountInStock: Path `CountInStock` is required
Mongoose ValidationError: Product validation failed: CountInStock: Path `CountInStock` is required

Time:05-11

I am a beginner to React.I am working in MERN stack project and I am following this tutorial. In my case, connection to the DB was success. However, I was unable to display products in my Home screen and when I tried with this link http://localhost:5000/api/seed nodemon app get crashed and display this error.

(node:28916) [MONGODB DRIVER] Warning: collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead. (Use `node --trace-warnings ...` to show where the warning was created) D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2965 this.$__.validationError = new ValidationError(this); ^

ValidationError: Product validation failed: CountInStock: Path CountInStock is required. at model.Document.invalidate (D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2965:32) at D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2754:17 at D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\schematype.js:1333:9 at processTicksAndRejections (node:internal/process/task_queues:78:11) {
errors: { CountInStock: ValidatorError: Path CountInStock is required. at validate (D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\schematype.js:1330:13) at SchemaNumber.SchemaType.doValidate (D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\schematype.js:1314:7) at D:\Github\Ecommerce-mern\backend\node_modules\mongoose\lib\document.js:2746:18 at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: { validator: [Function (anonymous)], message: 'Path CountInStock is required.', type: 'required', path: 'CountInStock', value: undefined }, kind: 'required', path: 'CountInStock', value: undefined, reason: undefined, [Symbol(mongoose:validatorError)]: true } }, _message: 'Product validation failed' } [nodemon] app crashed - waiting for file changes before starting...

Here is my Schema:

import mongoose from 'mongoose';

const productSchema = new mongoose.Schema(
  {
    name: { type: String, required: true, unique: true },
    slug: { type: String, required: true, unique: true },
    image: { type: String, required: true },
    brand: { type: String, required: true },
    category: { type: String, required: true },
    description: { type: String, required: true },
    price: { type: Number, required: true },
    CountInStock: { type: Number, required: true },
    rating: { type: Number, required: true },
    numReviews: { type: Number, required: true },
  },
  {
    timestamps: true,
  }
);

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

Here is my server.js:

import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import seedRouter from './routes/seedRoutes.js';
import productRouter from './routes/ProductRoutes.js';

dotenv.config();

mongoose
  .connect(process.env.MONGODB_URI)
  .then(() => {
    console.log('connected to db');
  })
  .catch((err) => {
    console.log(err.message);
  });

const app = express();
app.use('/api/seed', seedRouter);
app.use('/api/products', productRouter);


const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`server at http://localhost:${port}`);
});

And Here is my seedRoutes.js file :

import express from 'express';
import Product from '../models/productModel.js';
import data from '../data.js';

const seedRouter = express.Router();

seedRouter.get('/', async (req, res) => {
  await Product.remove({});
  const createdProducts = await Product.insertMany(data.products);
  res.send({ createdProducts });
});
export default seedRouter;

And my data.js file :

const data = {
  products: [
    {
      name: 'Nike Soccer Football',
      slug: 'nike-soccer-football',
      category: 'Shoes',
      image: '/images/p1.jpg',
      price: 120,
      countInStock: 10,
      brand: 'Nike',
      rating: 4.5,
      numReviews: 10,
      description: 'high quality pair of shoes',
    },
    {
      name: 'Adidas Soccer Football',
      slug: 'adidas-soccer-football',
      category: 'Shoes',
      image: '/images/p2.jpg',
      price: 250,
      countInStock: 0,
      brand: 'Adidas',
      rating: 4.0,
      numReviews: 10,
      description: 'high quality pair of shoes',
    },
    {
      name: 'Nike Slim Pant',
      slug: 'nike-slim-pant',
      category: 'Pants',
      image: '/images/p3.jpg',
      price: 65,
      countInStock: 5,
      brand: 'Nike',
      rating: 4.5,
      numReviews: 14,
      description: 'high quality product',
    },
    {
      name: 'Adidas Fit Pant',
      slug: 'Adidas-fit-pant',
      category: 'Pants',
      image: '/images/p4.jpg',
      price: 25,
      countInStock: 15,
      brand: 'Puma',
      rating: 4.5,
      numReviews: 10,
      description: 'high quality pair of shoes',
    },
  ],
};

export default data;

Can I know the error that I have done here? Is it regarding the file type that I have imported in server.js file?

CodePudding user response:

I think it is rather a typo. You have CountInStock in the schema definition, but countInStock in your data file. Javascript object keys are case-sensitive and therefore the case should match.

  • Related