1

最新的 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

4

2 回答 2

3

如果您已经在使用 Stitch,请查看Service Webhooks。Webhook 提供对 Stitch 函数的 HTTP 访问,并且 Stitch 函数支持$lookup.

Webhook 可能比使用 SDK 的查询更简单,因为在 JS 中管理管道有点复杂。SDK 仍可用于身份验证,但使用 webhook 访问的数据可能会使生活更轻松。

MongoDB 承诺10 分钟的 API 设置。我花了一点时间,但不多。

您的 Webhook 函数可能类似于:

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;
};

配置 webhook 后,您只需调用它。如果你使用 React,它看起来像这样:

  async componentDidMount() {
    const response = await fetch(MY_WEBHOOK);
    const json = await response.json();
    this.setState({ docs: json });
  }
于 2019-03-26T16:25:10.383 回答
2

您可以创建一个 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 => {...
于 2019-05-27T02:45:42.627 回答