KevinD
KevinD

Reputation: 140

Mongoose findOne based on another document causing unhandled Promise Rejection error

I have a MongoDB for my app, and in it I have one collection that is pay band data for a certain employee grade. I am trying to pull both the pay band for a specific grade, and for the next grade up, but am getting ah unhandled promise rejection error.

My test is looking for grade C.London, and I need to get the pay band for C.London and B.London. The documents in the db look like this:

{ "_id" : ObjectId("5c1cafe41d134100196750fa"), "gradeName" : "C.London", "minimum" : 53600, "midpoint" : 76550, "maximum" : 99500, "nextGrade" : "B.London", "__v" : 0 }
{ "_id" : ObjectId("5c1cafe41d134100196750de"), "gradeName" : "B.London", "minimum" : 53600, "midpoint" : 76550, "maximum" : 99500, "nextGrade" : "null", "__v" : 0 }

The code segment to get the values is:

// Get Pay bands
  let currentPayBand = await db.PayBand.findOne({
    gradeName: targetEmployee.grade
  });

  console.log(currentPayBand);

  if (currentPayBand.nextGrade) {
    let nextPayBand = await db.PayBand.findOne({
      gradeName: currentPayBand.nextGrade
    });
  } else {
    const nextPayBand = {
      minimum: null,
      midpoint: null,
      maximum: null
    }
  }

  console.log(nextPayBand);

It is finding the currentPayBand correctly, as the console.log is coming out correctly, but then it errors with the following error:

(node:25) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: nextPayBand is not defined

Upvotes: 0

Views: 175

Answers (1)

Charanjeet Singh
Charanjeet Singh

Reputation: 251

You are accessing the local variable outside the if. You may do like this or process in if conditions.

let nextPayBand = null

if (currentPayBand.nextGrade) {
  nextPayBand = await db.PayBand.findOne({
    gradeName: currentPayBand.nextGrade
  });
}
else {
  const nextPayBand = {
    minimum: null,
    midpoint: null,
    maximum: null
  }
}

console.log(nextPayBand)

Upvotes: 1

Related Questions