【发布时间】:2020-09-03 11:57:06
【问题描述】:
:) 我在与 MongoDB 的聚合中使用 $function 时遇到了错误。我有一个应该从以下开始的聚合:
db.collection.aggregate([
{
$addFields: {
geohash: {
$function: {
body: function (coord1, coord2) {
let geohash = Geohash.encode(coord1, coord2);
return geohash
},
args: [
"$location.coordinates[0]",
"$location.coordinates[1]",
],
lang: "js",
},
},
},
},
])
但是,当我运行查询时,它给了我这个错误: UnhandledPromiseRejectionWarning: MongoError: Invalid $addFields :: 由 :: 必须指定正文函数。
我使用的是 Mongo 4.4 版,并在 Node.Js 函数中运行此代码。任何帮助将非常感激。谢谢转发。 :)
顺便说一句,作为参考,我使用了这个文档:https://docs.mongodb.com/manual/reference/operator/aggregation/function/
【问题讨论】:
-
你在哪里定义了这个函数
Geohash.encode? -
@turivishal 这是一个名为 Ngeohash 的模块。我用 const Geohash = require("ngeohash"); 导入了它
-
我认为你不能访问任何外部函数,它可以允许访问默认的 nmongodb 运算符表达式函数检查 this 并且在 $function 中你可以定义你的自定义逻辑和代码。
标签: javascript node.js mongodb