1

I have this node.js app which retrieving subway data from mongodb using mongoose, and after I get the data, I will pass it to sphere-knn to calculate the nearest points. The strange thing happen in var lookup = sphereKnn(d1); if I pass d1 which is hard coded array, the code will work, if I pass the data which is retrieved from mongodb, it won't work at all, and returns empty array as result.

JSON.stringify(data) == JSON.stringify(d1) will print true, Array.isArray will also print true for both d1 and data, console.log will show there are data inside variable data.

I'm confused by the behaviour of the code. I came from .net and new to node.js. do I miss any important concept here?

mrtStop.find({}, {_id:0}, function(err, data){
  if(err){
    return res.json(err);
  }

  // data returned from mongodb, get first one
  data = data.slice(0,1);

  // hard coded data
  var d1 = [{"id":"EW6",
            "name":"EXAMPLE MRT STATION",
            "lat":1.3210355412,
            "lon":103.9129310102,
            "__v":0}];

  console.log(JSON.stringify(data));
  console.log(JSON.stringify(d1));
  // print true
  console.log(JSON.stringify(data) == JSON.stringify(d1));

  // d1 works, but data won't work
  // var lookup = sphereKnn(d1);
  var lookup = sphereKnn(data);

  var points = lookup(req.query.lat, req.query.lon, maxNum);

  res.json(points);
});
6
  • Can you show all your log results? Commented May 6, 2016 at 5:41
  • Have you tried sphereKnn[data[0]] ? Commented May 6, 2016 at 5:42
  • console.log the data and let me know? Commented May 6, 2016 at 5:43
  • @RahatMahbub that wouldn;'t be the case, OP said d1 == data Commented May 6, 2016 at 5:44
  • OP used == but not ===. == does type conversion. So, i don't know. Commented May 6, 2016 at 5:48

1 Answer 1

2

Use Query.lean()

tldr; mongoose returns mongoose-doc object, which has many prototypes, when you lean it, it will return plain js object

//side note: you could also remove `__v` property {_id: 0, __v:0}
mrtStop.find({}, {_id:0}).lean().exec(function(err, data){
  if(err){
    return res.json(err);
  }
  var lookup = sphereKnn(data);
  var points = lookup(req.query.lat, req.query.lon, maxNum);
  res.json(points);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.