TypeError: Cannot read property 'resources' of undefined?

I want to create a Mongoose Scheme that's a few layers deep but getting an error :

Here is the code:

//Mongoose Model
const MissionSchema = new Schema({

name: {
    type: String,
  },
  objective: [
    {
      resources: [
        {
          x: { type: Number },
          y: { type: Number }
        }
      ]
    }
  ] 
});

// @POST api/mission
// @desc Create A Mission

router.post('/', (req, res) => {

const newMission = new MissionModel({
    name: req.body.name,
    x: req.body.objective.resources.x
  });

  newMission.save().then(mission => res.json(mission));
});

I keep getting an error message in my console when testing with Postman

TypeError: Cannot read property resources of undefined?

  • mission name
    • mission objective
      • mission resources
        • mission resources #

2 answers

  • answered 2018-07-12 06:05 getDamir

    Whenever you get this error:

    TypeError: Cannot read property *propertyName* of undefined

    It means that you are calling it on wrong object or trying to read something that doesn't exist.

    In your case it means that in this part of code:

    x: req.body.objective.resources.x
    

    Your req.body.objective is undefined. You are either referencing the wrong object or it simply returns undefined.


    Solution: There are a few things you can do. But first, you should use console.log(req.body.objective) on that line and see what it logs.

  • answered 2018-07-12 11:07 Shubham Verma

    You are getting:

    TypeError: Cannot read property resources of undefined

    because, in your request body, objective is not available or objective property is undefined

    So you need to maintain the flow of execution by using some logic, here I am using the ternary operator:

    So your code will be:

    router.post('/', (req, res) => {
    
    const newMission = new MissionModel({
    
        name: req.body.name,
           x: req.body.objective?(req.body.objective.resources?req.body.objective.resources:'Missing Data is resource'):'Missing data is objective';
      });
    
      newMission.save().then(mission => res.json(mission));
    });