uni-app中请大家帮忙看看这个聚合操作为什么不行

uni-app中请大家帮忙看看这个聚合操作为什么不行

db.collection('Info')  
    .aggregate()  
    .addFields({  
        Degree: getDistance('$OriginLatitude','$OriginLongitude','$DestinationLatitude','$DestinationLongitude')  
    })  
    .end()  
    .then(res => {  
        console.log(res)  
    })  
    .catch(err => {  

    })

云函数中,聚合使用addFields时,getDistance是自定义函数,里面用了$OriginLatitude这些字段变量,得到的Degreenull,是语法不对吗?把$OriginLatitude这些变量写成阿拉伯数字就能正常运行。

报错信息如下:

Error: errCode: InternalServerError | errMsg: Command failed with error 40177 (Location40177): 'Invalid $addFields :: caused by :: specification must have at least one field' on server 192.168.146.77:3717. The full response is { "operationTime" : { "$timestamp" : { "t" : 1623577982, "i" : 114 } }, "ok" : 0.0, "errmsg" : "Invalid $addFields :: caused by :: specification must have at least one field", "code" : 40177, "codeName" : "Location40177", "$clusterTime" : { "clusterTime" : { "$timestamp" : { "t" : 1623577982, "i" : 114 } }, "signature" : { "hash" : { "$binary" : "b+SJ2ETY9Y1viMlZiPRk84oQMq4=", "$type" : "00" }, "keyId" : { "$numberLong" : "6941880109229932637" } } }

好难理解,为啥呢这是?难道是bug吗?


更多关于uni-app中请大家帮忙看看这个聚合操作为什么不行的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复

不可以使用自定义函数,你的自定义函数会先将结果输出出来

更多关于uni-app中请大家帮忙看看这个聚合操作为什么不行的实战教程也可以访问 https://www.itying.com/category-93-b0.html


计算Degree是个比较复杂的算式,需要用到’$OriginLatitude’等数据库字段,也需要用到数据库外面传进来的几个值,不使用自定义函数的话,如何进行计算呢?卡在这过不去了,麻烦大佬指点一下,感谢!

求大佬帮忙解决以下,卡在这真的是没办法了。。。

回复 Neveregret: 查询出来再计算

这个错误并不是bug,而是MongoDB聚合管道的语法限制导致的。

错误信息"specification must have at least one field"表明addFields操作中至少需要一个有效的字段定义。当getDistance函数返回null时,实际上整个addFields阶段没有产生任何有效的字段更新,因此触发了这个错误。

问题在于云函数环境中的聚合管道无法直接识别和调用客户端自定义的JavaScript函数。getDistance在云函数聚合上下文中无法正确解析$OriginLatitude等字段变量,导致函数返回null

正确的做法是使用MongoDB内置的地理空间查询操作符。在uni-app的云函数中,应该这样写:

db.collection('Info')
  .aggregate()
  .addFields({
    Distance: {
      $sqrt: {
        $add: [
          { $pow: [{ $subtract: ['$OriginLatitude', '$DestinationLatitude'] }, 2] },
          { $pow: [{ $subtract: ['$OriginLongitude', '$DestinationLongitude'] }, 2] }
        ]
      }
    }
  })
  .end()
回到顶部