Mongoose ValidationError: Product validation failed: CountInStock: Path `CountInStock` is required

Mongoose ValidationError: Product validation failed: CountInStock: Path `CountInStock` is required

我是 React.I 的初学者,正在 MERN 堆栈项目中工作,我正在学习 this 教程。就我而言,与数据库的连接是成功的。但是,我无法在主屏幕上显示产品,当我尝试使用此 link http://localhost:5000/api/seed nodemon 应用程序崩溃并显示此错误时。

(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...

这是我的架构:

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;

这是我的 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}`);
});

这是我的 seedRoutes.js 文件:

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;

还有我的 data.js 文件:

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;

我能知道我在这里犯的错误吗?是关于我在server.js文件中导入的文件类型吗?

我认为这是一个错字。您在架构定义中有 CountInStock,但在数据文件中有 countInStock。 Javascript 对象键是 case-sensitive,因此大小写应该匹配。