Reputation: 23
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 ;
};
Upvotes: 1
Views: 415
Reputation: 1260
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.
Upvotes: 2