0

I am using following code to update database in node.js

var mBooking = rows[0];
var distance = mBooking.distanceTravelled;
var lastLng = mBooking.lastLng;
var lastLat = mBooking.lastLat;

if(lastLat == 0)
{
    lastLat = lat;
    lastLng = lng;
}

var currentPoint = new GeoPoint(lat, lng);
var oldPoint     = new GeoPoint(lastLat, lastLng);

distance = distance + (currentPoint.distanceTo(oldPoint, true) * 1000);
if(distance == null)
    distance = 0;

var query = "UPDATE bookings SET lastLat = " + lat + ", lastLng = " + lng + ", distanceTravelled = " + distance + " WHERE id = " + mBooking.id;
console.log(query);

This is my console query

UPDATE bookings SET lastLat = 25.0979065, lastLng = 55.1634082, distanceTravelled = NaN WHERE id = 43

How can i put a check to see if distance is NaN then i can replace it with 0.

For now if i try to update it gives database error

Tushar
  • 85,780
  • 21
  • 159
  • 179
Muhammad Umar
  • 11,391
  • 21
  • 91
  • 193
  • IsNaN is what you're looking for – Jaromanda X Nov 30 '15 at 06:23
  • Auto correct. I shouldn't post on my phone – Jaromanda X Nov 30 '15 at 06:25
  • 2
    @JaromandaX SOAddict :) – Tushar Nov 30 '15 at 06:26
  • There is a function this `IsNaN` function which you can use as stated in comments. But I would advise you to avoid it as it does validate some strings("1E656716",etc) and could be unrelaible if want the `distance` to be validated as integers.
    So I suggest to add a custom function in your application. Something like below:- function isInteger(distance) { return typeof distance === "number" && isFinite(distance) && Math.floor(distance) === distance; }
    – Viraj Nalawade Nov 30 '15 at 06:33

1 Answers1

2

Use isNaN().

if (isNaN(distance))
    distance = 0;

You can also condense this to one line with an inline-if:

distance = (isNaN(distance) ? 0 : distance);
apscience
  • 7,033
  • 11
  • 55
  • 89