Reputation: 961
I am trying to get the latitude and longitude from a object. Why is it returning Undefined?. I am using .find() beacuse of this: https://blog.serverdensity.com/checking-if-a-document-exists-mongodb-slow-findone-vs-find/
var LatLngs = Shops.find({_id:template.data._id}, {fields: {latitude: 1, longitude: 1}, limit:1}).fetch(); console.log(LatLngs);
Console:
[Object] 0: Object_id: "vNHYrJxDXZm9b2osK" latitude: "xx.x50785" longitude: "x.xx4702" __proto__: Objectlength: 1 __proto__: Array[0]
try 2:
var LatLngs = Shops.find({_id:template.data._id}, {fields: {latitude: 1, longitude: 1}, limit:1}).fetch(); console.log(LatLngs.longitude);
Console:
undefined
Upvotes: 1
Views: 226
Reputation: 64342
fetch returns an array. In your first example you'd need to do something like this:
// fetch an array of shops
var shops = Shops.find(...).fetch();
// get the first shop
var shop = shops[0];
// if the shop actually exsists
if (shop) {
// do something with one of its properies
console.log(shop.latitude);
}
The linked article doesn't apply in this case - you are not testing if it exists, you are actually fetching it and reading its contents.
Use findOne instead:
// get a matching shop
var shop = Shops.findOne(...);
// if the shop actually exsists
if (shop) {
// do something with one of its properies
console.log(shop.latitude);
}
Upvotes: 1
Reputation: 22696
The fetch
method of Mongo cursors returns an array, so you have to access the longitude of the first item in the array : LatLngs[0].longitude
.
Moreover, you're working on the client, thus using MiniMongo, a browser reimplementation of the Mongo query language : you can't make the same assumptions on how findOne
will perform versus find
because it's not the same implementation as regular server-side MongoDB engine.
Just use findOne
, it has been specifically designed for your use case.
Upvotes: 1