title: How to add to mongodb, MERN app validation failed error
body: <p>I'm trying to learn the MERN stack, I'm trying to create a simple shopping list app.</p>
  
  <p>I have a simple api to get, post and delete items, this all works using Postman when testing the api.</p>
  
  <p>Locally the get works and I can get items from the db.</p>
  
  <p>When I try to add to the db I get this error.</p>
  
  <pre><code>(node:28550) UnhandledPromiseRejectionWarning: ValidationError: item validation failed: name: Path `name` is required.
  [0]     at new ValidationError (/Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/error/validation.js:30:11)
  [0]     at model.Document.invalidate (/Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/document.js:2080:32)
  [0]     at p.doValidate.skipSchemaValidators (/Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/document.js:1943:17)
  [0]     at /Users/user/Documents/_Work/cd/MERN/merntest-redux-1/node_modules/mongoose/lib/schematype.js:933:9
  [0]     at _combinedTickCallback (internal/process/next_tick.js:131:7)
  [0]     at process._tickCallback (internal/process/next_tick.js:180:9)
  [0] (node:28550) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
  [0] (node:28550) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
  </code></pre>
  
  <p>As the api works in postman I think it must be something to do the redux I'm using.</p>
  
  <p>ShoppingList js</p>
  
  <pre><code>import React, {Component} from 'react';
  import uuid from 'uuid';
  import {connect} from 'react-redux';
  import {getItems, deleteItem, addItem} from '../actions/itemActions';
  
  class ShoppingList extends Component{
  
    componentDidMount(){
      this.props.getItems()
    }
  
    onDeleteClick = (id) =&gt; {
      this.props.deleteItem(id);
    }
  
    render(){
  
      const {items} = this.props.item
  
      return(
        &lt;div&gt;
          &lt;button
            onClick={() =&gt; {
              const name = prompt('New Item')
  
              if(name){
                this.props.addItem(name)
              }
            }}
          &gt;
            Add Item
          &lt;/button&gt;
          &lt;ul&gt;
            {items.map(({id,name}) =&gt;{
              return(
                &lt;li key={id}&gt;
                  &lt;button
                    onClick={this.onDeleteClick.bind(this, id)}
                  &gt;
                    &amp;times;
                  &lt;/button&gt;
                  {name}
                &lt;/li&gt;
              )
            })}
          &lt;/ul&gt;
        &lt;/div&gt;
      )
    }
  
  }
  
  const mapStateToProps = state =&gt; ({
    item: state.item
  })
  
  export default connect (mapStateToProps, {getItems, deleteItem, addItem})(ShoppingList)
  </code></pre>
  
  <p>itemActions</p>
  
  <pre><code>import axios from 'axios';
  import {GET_ITEMS, ADD_ITEM, DELETE_ITEM, ITEMS_LOADING} from '../actions/types';
  
  export const getItems = () =&gt; dispatch =&gt;{
    dispatch(setItemsLaoding());
    axios
      .get('/api/items')
      .then(res =&gt; 
        dispatch({
          type: GET_ITEMS,
          payload: res.data
        })
      )
  }
  
  export const addItem = (name) =&gt; dispatch =&gt;{
    axios 
      .post('/api/items', name)
      .then(res =&gt; 
        dispatch({
          type: ADD_ITEM,
          payload: res.data
        })
      )
  }
  
  export const deleteItem = (id) =&gt;{
    return{
      type: DELETE_ITEM,
      payload: id
    }
  }
  
  export const setItemsLaoding = () =&gt; {
    return{
      type: ITEMS_LOADING
    }
  }
  </code></pre>
  
  <p>itemReducer.js</p>
  
  <pre><code>import {GET_ITEMS, ADD_ITEM, DELETE_ITEM, ITEMS_LOADING} from '../actions/types';
  
  const initialState = {
    items: [],
    loading: false
  }
  
  export default function(state = initialState, action){
    switch(action.type){
      case GET_ITEMS:
        return{
          ...state,
          items: action.payload,
          loading:false
        }
      case DELETE_ITEM:
        return{
          ...state,
          items: state.items.filter(item =&gt; item.id !== action.payload)
        }  
      case ADD_ITEM:
        return{
          ...state,
          items: [...state.items, { name: action.payload}]
        }  
      case ITEMS_LOADING:
        return{
          ...state,
          loading:true
        }
      default:
        return state  
    }
  }
  </code></pre>
  
  <p>models/Item.js (mongoose model)</p>
  
  <pre><code>const mongoose = require('mongoose');
  const Schema = mongoose.Schema;
  
  const ItemSchema = new Schema({
    name:{
      type: 'String',
      required: true 
    },
    Date:{
      type: Date,
      default: Date.now
    }
  })
  
  module.exports = Item = mongoose.model('item', ItemSchema); 
  </code></pre>
  
  <p>routes/api/items.js</p>
  
  <pre><code>const express = require('express');
  const router = express.Router();
  
  const Item = require('../../models/Item');
  
  router.get('/', (req, res) =&gt; {
      Item.find()
          .then(items =&gt; res.json(items))
          .catch(err =&gt; console.log(err))
  });
  
  router.post('/', (req, res) =&gt; {
      const newItem = new Item({
          name: req.body.name
      })
      newItem
          .save()
          .then(item =&gt; res.json(item))
          .catch(err =&gt; console.log(err))
  })
  
  router.delete('/:id', (req, res) =&gt;{
      Item.findById(req.params.id)
          .then(item =&gt; item.remove().then(() =&gt; res.json({success:true})))
          .catch(err =&gt; err.status(404).json({success:false}))
  })
  
  module.exports = router;
  </code></pre>