This tutorial demonstrates enriching MongoDB documents with data from an external API using MongoDB Stitch. We'll add movie details from the OMDB API to a MongoDB document after initial insertion.
Goal: This tutorial shows how to:
_id
and a Title
.Prerequisites:
You'll need a free MongoDB Atlas cluster. A video tutorial outlining the setup process is available (link presumably provided in the original). Then, link a MongoDB Stitch application to your Atlas cluster:
Setting up the HTTP POST Service:
The following function code will handle the initial document insertion:
exports = function(payload, response) { const mongodb = context.services.get("mongodb-atlas"); const movies = mongodb.db("stitch").collection("movies"); var body = EJSON.parse(payload.body.text()); movies.insertOne(body) .then(result => { response.setStatusCode(201); }); };
Save the function. Test it using a curl
command (or Postman) like this, replacing the placeholder URL and secret:
curl -H "Content-Type: application/json" -d '{"Title":"Guardians of the Galaxy"}' https://webhooks.mongodb-stitch.com/api/client/v2.0/app/stitchtapp-abcde/service/IMDB/incoming_webhook/post_movie_title?secret=test
Verify the insertion in your MongoDB Atlas cluster.
Creating the Trigger and Enrichment Function:
exports = function(changeEvent) { var docId = changeEvent.documentKey._id; var title = encodeURIComponent(changeEvent.fullDocument.Title.trim()); var movies = context.services.get("mongodb-atlas").db("stitch").collection("movies"); var imdb_url = "http://www.omdbapi.com/?apikey=[YOUR_OMDB_API_KEY]&t=" + title; const http = context.services.get("IMDB"); return http .get({ url: imdb_url }) .then(resp => { var doc = EJSON.parse(resp.body.text()); movies.updateOne({"_id":docId}, {$set: doc}); // Use $set to update only the new fields }); };
Remember to replace [YOUR_OMDB_API_KEY]
with your actual OMDB API key (obtain one from https://www.php.cn/link/fcf70ea0bbeb4edca72cc304e75f4c98). The $set
operator is used to prevent overwriting existing fields.
Test the trigger by sending another curl
request. The updated document should now contain the enriched movie data.
Summary:
This process demonstrates a powerful way to integrate external APIs with your MongoDB data using MongoDB Stitch's serverless capabilities. The event-driven architecture allows for efficient data enrichment without complex server-side logic.
Further Reading:
The above is the detailed content of How to Enrich Data with MongoDB Stitch. For more information, please follow other related articles on the PHP Chinese website!