Search code examples
mongodb-stitch

How to create a stitch Service with query params


I'm creating a Data API with MongoDB Stitch and i want to know how to create a function with query params (the params must be given when i call my API) i want to give like parametre the collection name when i call my API.

there is my Function

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

Solution

  • Here is a minimalist example of such a function:

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

    Test in Stitch Function Editor:

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

    Test outside Stitch (e.g. in Postman)

    Use the Webhook URL generated by Stitch, then append the query parameter.

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