0
votes

I am trying to get a random geometry from a PostGIS enabled PostgreSQL database using nodejs, but when I attempt to even do the first query, to get the 'max' automatically-generated, sequential ID in the dataset, it throws the above error. I recognise that the error is because it's expecting a string rather than a numeric value, but as the 'gid' field is numeric, i'm not sure how to solve this.

Any help explaining the issue/fixing it so I can get my random object from the database would be extremely helpful. Thanks in advance.

var db = new pg.Client(conString);
db.connect();

function getRandObj(){
    var max = db.query( " SELECT MAX(`gid`) FROM `buildings` ");
    //var min = db.query( " SELECT MIN(`gid`) FROM `buildings` ");
    //var random = mt_rand( min , max );
    //var result = db.query( " ST_AsGeoJSON(geom) FROM `buildings` WHERE `gid` >= random LIMIT 0,1 ");
    //return result
}
1

1 Answers

1
votes

I haven't messed with node.js too much, but, I have experimented a little. Looking at your code here:

var max = db.query( " SELECT MAX(`gid`) FROM `buildings` ");

I see a couple of potential issues. First, the backquotes. I think they are a mistake. Change that query to read:

var max = db.query( " SELECT MAX(gid) FROM buildings ");

Or, if you really want to see quotes in there, you should be using "name" quotes, like:

var max = db.query( ' SELECT MAX("gid") FROM "buildings" ');

The second thing is the return value. I don't think you get direct returns like that. Have you tried something like this:

var max = -1;
q = db.query(' SELECT MAX("gid") FROM "buildings" as mx ');

q.on('row', function (row) {
    console.log(row);
    max = row.mx;
};
console.log("max is %d", max);

-g