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

问题描述 投票:0回答:1

最新的Stitch不支持$ lookup吗?我正在使用[email protected],我的服务器是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的错误

javascript mongodb mongodb-stitch
1个回答
3
投票

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

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

MongoDB承诺10-minute API setup。我花了稍长的时间,但并不多。

您的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 });
  }

1
投票

您可以创建一个Stitch函数来执行此操作,并直接从您的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 => {...
© www.soinside.com 2019 - 2024. All rights reserved.