Skip to content

Instantly share code, notes, and snippets.

@tristansokol
Created October 21, 2017 18:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tristansokol/7953b4149a06023cd26c377faa5b6877 to your computer and use it in GitHub Desktop.
Save tristansokol/7953b4149a06023cd26c377faa5b6877 to your computer and use it in GitHub Desktop.
mongodb - google cloud functions write example
exports.helloWorld = function helloWorld(req, res) {
//Connect to MongoDB Atlas
var MongoClient = require('mongodb').MongoClient;
var uri = "mongodb://user:pass@cluster0-shard-00-00-6chsu.mongodb.net:27017,cluster-shard-00-01-6chsu.mongodb.net:27017,cluster-shard-00-02-6chsu.mongodb.net:27017/test?ssl=true&replicaSet=Cluster-shard-0&authSource=admin";
MongoClient.connect(uri, function(err, db) {
//check for connection errors
if (err) res.status(400).send(err);
//Read the data from the incoming request & add it to an object to insert
var message = req.body.message;
var myobj = { "message": message };
//Try to insert the object
db.collection("messages").insertOne(myobj, function(err, response) {
//check for insertion errors
if (err) res.status(400).send(err);
//If everything went well, return a 200 and success messsage!
res.status(200).send('Success: ' + req.body.message);
db.close();
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment