【问题标题】:Cannot acces object properties. Returns undefined (Meteor)无法访问对象属性。返回未定义(流星)
【发布时间】:2015-06-06 22:08:56
【问题描述】:

我正在尝试从对象获取纬度和经度。为什么它返回未定义?。我正在使用 .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

【问题讨论】:

    标签: javascript node.js mongodb object meteor


    【解决方案1】:

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

    此外,您正在客户端上工作,因此使用 MiniMongo,这是 Mongo 查询语言的浏览器重新实现:您不能对 findOnefind 的执行方式做出相同的假设,因为它不一样实现为常规的服务器端 MongoDB 引擎。

    只需使用findOne,它是专为您的用例设计的。

    【讨论】:

      【解决方案2】:

      fetch 返回一个数组。在您的第一个示例中,您需要执行以下操作:

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

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

      改用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);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-18
        • 1970-01-01
        • 2016-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-06
        • 2018-02-04
        相关资源
        最近更新 更多