无法访问对象属性。 返回undefined(meteor)

我试图从一个对象获取经纬度。 为什么它返回Undefined ? 我正在使用.find()使用这个: 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); 

安慰:

 [Object] 0: Object_id: "vNHYrJxDXZm9b2osK" latitude: "xx.x50785" longitude: "x.xx4702" __proto__: Objectlength: 1 __proto__: Array[0] 

试试2:

 var LatLngs = Shops.find({_id:template.data._id}, {fields: {latitude: 1, longitude: 1}, limit:1}).fetch(); console.log(LatLngs.longitude); 

安慰:

 undefined 

Mongo游标的fetch方法返回一个数组,因此您必须访问数组中的第一项的经度: LatLngs[0].longitude

此外,您正在使用客户端,因此使用MiniMongo(一种重新实现Mongo查询语言的浏览器):您无法对findOne如何执行和find有相同的假设,因为它与常规服务器端MongoDB不同发动机。

只要使用findOne ,它就是专门为你的用例devise的。

提取返回一个数组。 在你的第一个例子中,你需要做这样的事情:

 // 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); } 

链接的文章不适用于这种情况 – 你不testing它是否存在,你实际上是获取它并阅读它的内容。

改用findOne :

 // 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); }