MongoDB Stitch SDK返回“聚合阶段“不支持$ lookup””

时间:2019-03-18 03:19:36

标签: javascript mongodb mongodb-stitch

最新的Stitch是否不支持$ lookup?我正在使用mongodb-stitch-server-sdk@4.3.2,我的服务器版本为4.0.6。我有一个类似以下的查询:

const {
    Stitch,
    UserPasswordCredential,
    RemoteMongoClient
} = require('mongodb-stitch-server-sdk');

const client = Stitch.initializeDefaultAppClient('<APP ID>');
client.auth.loginWithCredential(new UserPasswordCredential("<username>","<password>")).then(user => {
    client.close();
}).catch(err => {
    console.log(err);
    client.close();
})


mongodb = client.getServiceClient(
  RemoteMongoClient.factory,
  "fleet-home")
testQuery =
  [{
    $match: {
      _id: "c1ba5c3f-263b-5748-9492-e50e0a39cb7a"
    }
  },
  {
    $lookup: {
      from: "aircraft",
      localField: "aircraft_id",
      foreignField: "_id",
      as: "aircraft"
    }
  }]

test = mongodb
.db("FleetDatabase")
.collection("fleet")
.aggregate(testQuery)
.asArray().then((success) => {
  console.log(success)
})

但是,我遇到了UnhandledPromiseRejectionWarning: StitchServiceError: aggregation stage "$lookup" is not supported

错误

2 个答案:

答案 0 :(得分:2)

如果您已经在使用Stitch,请查看Service Webhooks。 Webhooks提供对Stitch函数的HTTP访问,Stitch函数支持std::shared_ptr

Webhooks可能比使用SDK的查询更简单,因为在JS中管理管道会有些麻烦。该SDK仍可以用于身份验证,但是通过Webhooks访问的数据可能会使生活更轻松。

MongoDB承诺10-minute API setup。我花了一点时间,但是花了很多时间。

您的Webhook函数可能类似于:

$lookup

配置了Webhook之后,您只需调用它即可。如果您使用的是React,则如下所示:

exports = function() {
  var collection = context.services
    .get("mongodb-atlas")
    .db("FleetDatabase")
    .collection("fleet");
  var doc = collection
    .aggregate([
      {
        $match: {
          _id: "c1ba5c3f-263b-5748-9492-e50e0a39cb7a"
        }
      },
      {
        $lookup: {
          from: "aircraft",
          localField: "aircraft_id",
          foreignField: "_id",
          as: "aircraft"
        }
      }
    ])
    .toArray();

  return doc;
};

答案 1 :(得分:0)

您可以创建一个Stitch函数来执行此操作,然后直接从绣花客户端var(已将其命名为client)调用它:

请参阅:https://docs.mongodb.com/stitch/functions/define-a-function/

创建一个函数。如果您以system user的身份运行函数,那么您将不受限制地访问MongoDB CRUD和聚合操作:

请参阅:https://docs.mongodb.com/stitch/authentication/#system-users

然后调用该函数:

请参阅:https://docs.mongodb.com/stitch/functions/call-a-function/

在您的应用中,就像:

client.callFunction('functionName', args).then(response => {...