如何修复 Nodejs + Moongose API 中的验证错误?

问题描述 投票:0回答:3

我正在尝试通过我的 api 使用 nodejs 和 mongodb 创建产品用于电子商务管理库存,但验证时出现错误,以下是我使用过的代码。

这是我的 mongoose.js 代码

// require the library
const mongoose = require('mongoose');

require('dotenv').config();
// connecting database
mongoose.connect(process.env.MONGO_CONNECT);
// aquire the connection
const db = mongoose.connection;
//on error
db.on('error', console.error.bind(console, 'error connecting to db'));
// on success
db.once('open', function(){
    console.log('Successfully connected to the database');
})
// exporting db
module.exports = db;

这是我的架构

const mongoose = require('mongoose');

// Schema for Product [fields: id, name, quantity] with timeStamps
const productSchema = new mongoose.Schema({
    name:{
        type: String,
        required: true
    } ,
    quantity:{
        type: Number,
        required: true
    }
},{timestamps:true})

const Product = mongoose.model('Product', productSchema);
// exporting schema
module.exports = Product;

这是我的controllerproduct js文件

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

// Fetch List of products
module.exports.list = async function(req, res){
    try{
        let product = await Product.find()
        return res.status(200).json({
            data:{
                message: "Products",
                products: product
            }
        })
    }catch(err){
        console.log('Error in fetching List of products',err);
        return res.send('Error in fetching List of products'+ err);
    } 
}

// Create Product
module.exports.create = async function(req, res){
    try{
        let product = new Product({
            name: req.body.name,
            quantity: req.body.quantity,
        });
        await product.save() 
        return res.status(200).json({
            data:{
                message: "Product created",
                products: product
            }
        })
    }catch(err){
        console.log('Error in creating product',err);
        return res.send('Error in creating product'+ err);
    } 
}

// Delete Product
module.exports.delete = async function(req, res){
    try{
        let product= await Product.findById(req.params.id);
            await product.remove();
            return res.status(200).json({
                data:{
                    message: "Product removed from list",
                }
            })
    }catch(err){
        console.log('Error in removing product',err);
        return res.send('Error in removing product'+ err);
    } 
}

// Update quantity
module.exports.update = async function(req, res){
    try{
        let product= await Product.findById(req.params.id);
        // Here using req.query to update quantity [NOTICE: using number for query]
        let num = parseInt(req.query.number);
        if(product.quantity + num < 0){
            return res.status(200).json({
                data:{
                    message: "Try Again! Product quantity could not be less then 0",
                }
            })
        }else{
            product.quantity = product.quantity + num
            await product.save() 
            return res.status(200).json({
                data:{
                    message: "Product Quantity updated successfully",
                    products: product
                }
            })
        }
    }catch(err){
        console.log('Error in updating quantity of the product',err);
        return res.send('Error in updating quantity of the product:::'+ err);
    } 
}

module.exports.home = async function(req, res){
    try {
        return await res.send('Hello Admin')
    } catch (error) {
        console.log('Error at home',err);
        return res.send('Error at home page:'+ err);
    }
}

这是主index.js 文件

const express = require('express');
const port = process.env.PORT||8800;
const app = express();
const db = require('./config/mongoose');

// To parse incoming requests 
app.use(express.urlencoded());

// It parses incoming requests with JSON
app.use(express.json())

// making connection to index of route
app.use('/', require('./routes/index'))


// connecting to port
app.listen(port, function(err){
    if(err){
        console.log(`Error! connecting Port : ${err}`);
    }
    console.log(`Connected on Port : ${port}`);
})

我正在尝试使用邮递员通过我的 Api 创建产品,但我收到此错误,任何帮助将不胜感激:

Aditya Kumar@DESKTOP-980JOV2 MINGW64 ~/nodews/ecommerce-Api
$ node index.js
body-parser deprecated undefined extended: provide extended option index.js:7:17
Connected on Port : 8800
Successfully connected to the database
Error in creating product Error: Product validation failed: name: Path `name` is required., quantity: Path `quantity` is required.
    at ValidationError.inspect (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\error\validation.js:49:26)
    at formatValue (node:internal/util/inspect:782:19)
    at inspect (node:internal/util/inspect:347:10)
    at formatWithOptionsInternal (node:internal/util/inspect:2167:40)
    at formatWithOptions (node:internal/util/inspect:2029:10)
    at console.value (node:internal/console/constructor:324:14)
    at console.log (node:internal/console/constructor:360:61)
    at module.exports.create (C:\Users\Aditya Kumar\nodews\ecommerce-Api\controllers\product_controller.js:34:17)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  errors: {
    name: ValidatorError: Path `name` is required.
        at validate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1346:13)
        at SchemaString.SchemaType.doValidate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1330:7)
        at C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\document.js:2835:18
        at processTicksAndRejections (node:internal/process/task_queues:78:11) {
      properties: [Object],
      kind: 'required',
      path: 'name',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    },
    quantity: ValidatorError: Path `quantity` is required.
        at validate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1346:13)
        at SchemaNumber.SchemaType.doValidate (C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\schematype.js:1330:7)
        at C:\Users\Aditya Kumar\nodews\ecommerce-Api\node_modules\mongoose\lib\document.js:2835:18
        at processTicksAndRejections (node:internal/process/task_queues:78:11) {
      properties: [Object],
      kind: 'required',
      path: 'quantity',
      value: undefined,
      reason: undefined,
      [Symbol(mongoose:validatorError)]: true
    }
  },
  _message: 'Product validation failed'
}
javascript node.js mongoose postman
3个回答
0
投票

这可能是由于未配置 HTTP 请求标头,请确保您在调用 API 时通过添加

application/json
内容类型标头

发送有效的 JSON 负载

示例:

卷曲

curl -X POST http://localhost:8000 -d '{"name": "Dummy", "quantity": 1}' -H "Content-Type: application/json"

获取

const res = await fetch('http://localhost:8000', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  }
});

0
投票

req.body.name
最有可能出现为
undefined
。尝试将其登录到控制台,如果确实是
undefined
,那么可能是由于某些系统错误。您可以尝试重新启动服务器甚至本地计算机。

问题也可能来自于您在邮递员中发送的请求。确保所有参数都在正确的位置


0
投票

我也面临同样的问题,通过在主 index.js 文件中添加 body-parser 中间件解决了这个问题

npm i body-parser
const bodyParser = require("body-parser");
app.use(bodyParser.json());
© www.soinside.com 2019 - 2024. All rights reserved.