Can't add a document to the mongoDB database, getting an error: Path name is required

I'm trying to figure out what exactly is happening when i want to add a document to the mongoDB database.

When i try to add a document i'm getting this error:

{
 "errors": {
 "name": {
 "message": "Path `name` is required.",
 "name": "ValidatorError",
 "properties": {
 "type": "required",
 "message": "Path `{PATH}` is required.",
 "path": "name"
    },
 "kind": "required",
 "path": "name"
   }
  },
 "message": "Product validation failed",
 "name": "ValidationError"
 }

So i'm using Express Js and Mongoose to perform this action. In my model: product.js


var mongoose = require('mongoose'); 

var productSchema = new mongoose.Schema({
name: {type: String, required: true}, 
category: {type: String, default: ''}, 
price: { type: Number, default: 0}, 
picture: { type: String}, 
quantity: {type: Number, default: 0}, 
status: { 
    type: String, 
    enum: ['pending', 'In Progress', 'Cancelled', 'Done'], 
    default: 'pending' 
}, 
date: { type: Date, default: Date.now}, 
description: { type: String}, 
owner: {type: String}
}); 

var Product = mongoose.model('Product', productSchema); 

module.exports = Product; 

In my api routes, when i define the path for performing this action: index.js

var express = require('express'); 
var router = express.Router(); 
var productCtrl = require('../controllers/productCtrl'); 

router.get('/products', productCtrl.getAllProducts); 
router.get('/products/:productId', productCtrl.readProduct); 
router.post('/products', productCtrl.createProduct); 
router.delete('/products/:productId', productCtrl.removeProduct); 
router.put('/products/:productId', productCtrl.updateProduct); 

module.exports = router; 

Finally, in my controller file: productCtrl.js

var Product = require ('../models/products'); 
var sendJsonResponse = function(res, status, content) {
  res.status(status);
  res.json(content);
}
module.exports.createProduct = function (req, res){
Product
      .create({
        name: req.body.name, 
        category: req.body.category, 
        price: req.body.price, 
        picture: req.body.picture, 
        quantity: req.body.quantity,
        status: req.body.status, 
        date: req.body.date, 
        description: req.body.description, 
        owner: req.body.owner

      }, function createProduct(err, product){
        if(err){
            sendJsonResponse(res, 404, err); 
            return; 
        }
        else {
            sendJsonResponse(res, 201, product); 
        }
      });
 } 

The behavior excepted is that i should have product document returned in json format

About my environnement, I'm using :

node.js version: 6.9.4
mongodb version: 3.4.4
express version: ~4.13.4
mongoose version: ^4.9.8

I really need help guys

Upvotes: 0

Views: 949

Answers (2)

Anis Mokeddes
Anis Mokeddes

Reputation: 71

The exception means that the field "name" in your model is required (you set required=true), Check your req.body.name POST action.

express-validator module to perform both validation and sanitization of your data to avoid this problem. like this :

 req.checkBody('name', 'Product name required').notEmpty(); 
 var errors = req.validationErrors();
  //Run the validators
  var errors = req.validationErrors();
if (errors) {
    //If there are errors  data form invalid
    res.send('');
return;
} 
else {
    // Data from form is valid.
 }

You can try this :
productCtrl.js

var Product = require ('../models/products'); 
var sendJsonResponse = function(res, status, content) {
  res.status(status);
  res.json(content);
}
module.exports.createProduct = function (req, res){



  var new_product = new Product();//instance of object (model) product

        new_product.name: req.body.name, 
        new_product.category: req.body.category, 
        new_product.price: req.body.price, 
        new_product.picture: req.body.picture, 
        new_product.quantity: req.body.quantity,
        new_product.status: req.body.status, 
        new_product.date: req.body.date, 
        new_product.description: req.body.description, 
        new_product.owner: req.body.owner

   new_product.save(function(err, addprod) {//save your new product in database

   if (err){

     res.send(err);// error when save

     }

    res.send(addprod);//else return a product add

    });

  };

Upvotes: 1

FluffyNights
FluffyNights

Reputation: 292

The exception means that the field "name" in your model is required (you set required=true), but not provided, means you pass null or undefined to it

.create({
    name: req.body.name, 

req.body.name is probably undefined. Check your POST action and try console.log(req.body) to see if it is populated at all.

Upvotes: 1

Related Questions