node.js - mongoose/nodejs 中的验证错误

标签 node.js mongodb express mongoose

当我想将产品添加到数据库(MongoDB)时。程序处于循环模式并且不会崩溃,但它在控制台中显示错误。

Console content included on the bottom

models/single-product.js

// models/single-product.js

const mongoose = require('mongoose')

const Schema = mongoose.Schema

const productSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }
})

module.exports = mongoose.model('Product', productSchema)

模型/user.js

// models/user.js

const mongoose = require('mongoose')

const Schema = mongoose.Schema

const userSchema = new Schema({
    username: {
        type: String ,
        required: true
    },
    email: {
        type: String ,
        required: true
    },
    cart: {
        items:[
            {
               productId: {
                  type: Schema.Types.ObjectId,
                  ref: 'Product',
                  required: true
               }, 
               qty:{
                type: Number ,
                required: true
               }
            }
        ]
    }
})
module.exports =mongoose.model('User', userSchema)

Controller /admin.js

// constrollers/admin.js

const Product = require('../models/single-product')

module.exports.addProductsPage = (req,res)=> {
    res.render('admin/add-product',{
        pageTitle: "Add Product-Page"
    })
}

module.exports.sendProducts = (req,res)=>{
    const title = req.body.title
    const description = req.body.description
    const price = req.body.price
    const products = new Product({
        title: title,
        description: description ,
        price: price,
        userId: req.user
    })
    products.save()
    .then(result =>{
        console.log('Product Created!')
        res.redirect('/admin/add-product')
    })
    .catch(err =>{
        console.log(err)
    })
    
}
module.exports.getProducts = (req,res)=>{
    Product.find()
        .then(products =>{
            res.render('admin/products',{
                productsArray : products,
                pageTitle : 'Admin Products'
            })
        })
        .catch(err =>{
            console.log(err)
        })
}
module.exports.deleteProduct = (req,res)=>{
    const pId = req.body.productId
    Product.findByIdAndRemove(pId)
    .then(()=>{
        console.log('Product Deleted!')
        res.redirect('products')
    })
    .catch(err =>{
        console.log(err)
    })
}

Error [ValidationError]: Product validation failed: userId: Path `userId` is required.
at ValidationError.inspect (D:\Alireza\web\Test project's\OnlineShop-Node.js\node_modules\mongoose\lib\error\validation.js:59:24)
at formatValue (internal/util/inspect.js:550:31)
at inspect (internal/util/inspect.js:221:10)
at formatWithOptions (internal/util/inspect.js:1651:40)
at Object.Console.<computed> (internal/console/constructor.js:272:10)
at Object.log (internal/console/constructor.js:282:61)
at D:\Alireza\web\Test project's\OnlineShop-Node.js\controllers\admin.js:25:17
at processTicksAndRejections (internal/process/task_queues.js:85:5) {

错误:{ userId:MongooseError [ValidatorError]:路径 userId 是必需的。 在新的 ValidatorError (D:\Alireza\web\Test 项目的\OnlineShop-Node.js\node_modules\mongoose\lib\error\validator.js:29:11) 在验证(D:\Alireza\web\Test 项目的\OnlineShop-Node.js\node_modules\mongoose\lib\schematype.js:1034:13) 在 D:\Alireza\web\Test 项目的\OnlineShop-Node.js\node_modules\mongoose\lib\schematype.js:1088:11 在Array.forEach() 在 ObjectId.SchemaType.doValidate (D:\Alireza\web\Test 项目的\OnlineShop-Node.js\node_modules\mongoose\lib\schematype.js:1043:14) 在 D:\Alireza\web\Test 项目的\OnlineShop-Node.js\node_modules\mongoose\lib\document.js:2134:9 在 processTicksAndRejections (内部/process/task_queues.js:75:11) { message: '路径 userId 是必需的。', name: '验证器错误', 属性:[对象], 种类:“必需”, 路径:'用户ID', 值:未定义, 原因:未定义, [符号( Mongoose :validatorError)]:true } }, _message: '产品验证失败', 名称:'验证错误' }

enter image description here

最佳答案

首先检查req.user是否不为空,然后使用

保存产品
const products = new Product({
        title: title,
        description: description ,
        price: price,
        userId: mongoose.Types.ObjectId(req.user);
    })

you need to make userId as objectID

关于node.js - mongoose/nodejs 中的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57176032/

相关文章:

javascript - 在 mongodb 中实现分页

node.js - 如何通过 Express Route 使用 Mongoose-Crate 存储文件

c# - MongoDB C# SSL 客户端证书

javascript - 格式化从 PostgreSql 数据库检索的 JSON 数据

node.js - Express 4 火灾事件结束

javascript - JQuery 表单插件向 Node.js 发送空数据?

windows - 从NodeJs启动一个独立的进程

javascript - 是否可以获取 NodeJS 代码中调用的 package.json 脚本?

javascript - 在 Node js 中使用 AJAX 并使用 Handlebars 显示数据

javascript - 是否可以在 React Native 中填充 Node 的 fs.readFileSync() ?