【问题标题】:UnhandledPromiseRejectionWarning: MongoError: Invalid $addFields :: caused by :: The body function must be specifiedUnhandledPromiseRejectionWarning: MongoError: Invalid $addFields :: 由 :: 必须指定body函数
【发布时间】: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


【解决方案1】:

我之前尝试过同样的事情,我发现,函数体必须是字符串,而且您似乎无法访问外部函数。所以你的问题的解决方案可能是这样的:

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'
      },
    }];

【讨论】:

  • 它是否适用于 nodejs?它适用于 mongo shell 我尝试了这个,但当我使用 mongo 客户端和 mongoose 更新时不适用于 nodejs。
  • 它适用于 mongodb 和 nodejs,但不适用于 mongoose。您需要为 nodejs 使用本机 mongodb 驱动程序
  • 这绝对适用于 mongoose,MongoDB 版本 4.4.2
猜你喜欢
  • 2021-10-31
  • 2021-10-01
  • 2020-03-06
  • 2018-12-11
  • 1970-01-01
  • 2021-12-14
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多