3

When I want to add products to the database (MongoDB) . The program is in loop mode and does not crash, but it shows the error in the console.

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)

models/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)

controllers/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) {

errors: { userId: MongooseError [ValidatorError]: Path userId is required. at new ValidatorError (D:\Alireza\web\Test project's\OnlineShop-Node.js\node_modules\mongoose\lib\error\validator.js:29:11) at validate (D:\Alireza\web\Test project's\OnlineShop-Node.js\node_modules\mongoose\lib\schematype.js:1034:13) at D:\Alireza\web\Test project's\OnlineShop-Node.js\node_modules\mongoose\lib\schematype.js:1088:11 at Array.forEach () at ObjectId.SchemaType.doValidate (D:\Alireza\web\Test project's\OnlineShop-Node.js\node_modules\mongoose\lib\schematype.js:1043:14) at D:\Alireza\web\Test project's\OnlineShop-Node.js\node_modules\mongoose\lib\document.js:2134:9 at processTicksAndRejections (internal/process/task_queues.js:75:11) { message: 'Path userId is required.', name: 'ValidatorError', properties: [Object], kind: 'required', path: 'userId', value: undefined, reason: undefined, [Symbol(mongoose:validatorError)]: true } }, _message: 'Product validation failed', name: 'ValidationError' }

enter image description here

3 Answers 3

2

First check if req.user is not null, then save product using

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

you need to make userId as objectID

Sign up to request clarification or add additional context in comments.

2 Comments

Tnx @Vinil . I edited userId to mongoose.Types.ObjectId(req.user) , And the problem was fixed. Thank you so much .
You are most welcome, please accept the answer if it helped
1

Change the Content-Type property which by default is text/plain.
Because of this text/plain MongoDB doesn't validate your request.

Content-Type: text/plain; // Previous Value
Content-Type: application/json // Changed value

Comments

0

Please check This Section of Code in controllers/admin.js.

const products = new Product({
        title: title,
        description: description ,
        price: price,
        userId: req.user
    })

you are inserting the userId with an undefined or null value. I think req.user is undefined and as you defined the schema of userId column with required true constraints in you model:

userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    }

Please check this log before inserting the data

console.log(req.user);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.