:)
我在与 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'
},
}];
关于javascript - UnhandledPromiseRejectionWarning: MongoError: Invalid $addFields::由::必须指定body函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63723164/