2

我正在使用 MongoDB Stitch 创建一个数据 API,并且我想知道如何使用查询参数创建一个函数(当我调用我的 API 时必须给出参数)我想在调用我的 API 时像参数一样给出集合名称。

有我的功能

exports = function(arg) {
const mongodb = context.services.get("mongodb-atlas");
const mycollection = mongodb.db("STM32").collection(arg);
console.log(arg) ;
var array = mycollection.find({}).toArray();  
return array ;
};
4

1 回答 1

2

这是此类功能的极简示例:

exports = function(payload, response) {
  // retrieve collection name from querystring (e.g. ?coll=myCollection)
    const {coll} = payload.query;

    // log collection name to confirm receipt from querystring
    console.log("collection name passed: ", coll);

    // query a mongodb service, passing the parameterized collection name
    const doc = context.services.get("mongodb-atlas").db("mydb").collection(coll).find().toArray();

    return  doc;
};

在缝合功能编辑器中测试

exports({query: {coll: 'myCollection'}})

在 Stitch 外部测试(例如在Postman中)

使用 Stitch 生成的Webhook URL,然后附加查询参数。

https://webhooks.mongodb-stitch.com/api/client/v2.0/app/MY_STITCH_APP_ID/service/http/incoming_webhook/MY_WEBHOOK_NAME?coll=myCollection

于 2019-06-20T18:27:48.343 回答