Friday, 12 May 2017

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



via Joel Alexandre Khang

No comments:

Post a Comment