skip to Main Content

I created an API for my project but in an endpoint, there occurred an error that I couldn’t fix.

const fullOrdersForService = service.totalOrders
const updatedFullOrdersForService = fullOrdersForService + 1
const updateService = await Service.findOneAndUpdate({_id:serviceId}, { totalOrders: updatedFullOrdersForService },{new:true})

Absolutely in the above code, I checked the type of service.totalOrders and its output as the number and also service.totalOrders came from a schema so there isn’t any possibility to change the type of that into string or NaN. I checked whether it is NaN and it is also false and it is not a NaN. I still wonder how that error occurred.
But an error occured like following.

messageFormat: undefined,
stringValue: '"NaN"',
kind: 'Number',
value: NaN,
path: 'totalOrders',
reason: AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:
assert.ok(!isNaN(val))

My schema of the Service.totalOrders can be seen in the below.

totalOrders:{
  type:Number,
  required:true,
  default:0
}

My schema of the Seller.totalOrders can be seen in the below.

totalOrders:{
  type:Number,
  required:true,
  default:0
}
const fullOrdersForService = service.totalOrders  
const updatedFullOrdersForService = fullOrdersForService + 1 
const updateService = await Service.findOneAndUpdate({_id:serviceId}, { totalOrders: updatedFullOrdersForService },{new:true})

I just tried this code and the error which I mentioned above occurred.

2

Answers


  1. first console.log(fullOrdersForService ) and console.log(updatedFullOrdersForService ) to check wather it’s number or not then

    if updatedFullOrdersForService is correct but string use parseInt(updatedFullOrdersForService ) before updating

    Login or Signup to reply.
  2. You can use $inc to increment your value without relying on external variables:

    const updateService = await Service.findOneAndUpdate(
        { _id: serviceId },
        { $inc: { totalOrders: 1 } },
        { new: true }
      );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search