:) 我在 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/
我之前尝试过同样的事情,我发现函数体必须是字符串,而且似乎你无法访问外部函数。所以你的问题的解决方案可能是这样的:
db.collection.aggregate([
{
$addFields: {
geohash: {
$function: {
body: `function (coord1, coord2) {
// NOTE: you need to define Geohash inside the function
let geohash = Geohash.encode(coord1, coord2);
return geohash
}`,
args: [
"$location.coordinates[0]",
"$location.coordinates[1]",
],
lang: "js",
},
},
},
},
])
这是我之前尝试过的:
const updateDocEx = [{
$set: {
status: 'Modified',
comments: {
$function: {body: `function (val, newVal) {
const vx = '';
const v1 = !val ? newVal : vx.concat(val, ',', newVal);
const v2 = v1.split(',');
const v3 = [...new Set(v2)];
return v3.join(',');
}`, args: ['$comments', 'A5'], lang: 'js'}
},
lastUpdate: '$$NOW'
},
}];
添加选项 const 选项 = { serializeFunctions: true } 一旦你给出这个选项,它就会起作用。