Created
February 26, 2019 18:49
-
-
Save MickaelBaye/f99dd604fbd12af1a1143a6948f077ae to your computer and use it in GitHub Desktop.
MongoDB Stitch Basic Blog tutorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4/stitch.js"></script> | |
<script> | |
// Initialize the App Client | |
const client = stitch.Stitch.initializeDefaultAppClient("<APP-ID>"); | |
// Get a MongoDB Service Client | |
const mongodb = client.getServiceClient( | |
stitch.RemoteMongoClient.factory, | |
"mongodb-atlas" | |
); | |
// Get a reference to the blog database | |
const db = mongodb.db("blog"); | |
function displayComments() { | |
db.collection("comments") | |
.find({}, {limit: 1000}) | |
.toArray() | |
.then(docs => { | |
const html = docs.map(doc => `<div>${doc.comment}</div>`); | |
document.getElementById("comments").innerHTML = html; | |
}); | |
} | |
function displayCommentsOnLoad() { | |
client.auth | |
.loginWithCredential(new stitch.AnonymousCredential()) | |
.then(displayComments) | |
.catch(console.error); | |
} | |
function addComment() { | |
const newComment = document.getElementById("new_comment"); | |
console.log("add comment", client.auth.user.id) | |
db.collection("comments") | |
.insertOne({ owner_id : client.auth.user.id, comment: newComment.value }) | |
.then(displayComments); | |
newComment.value = ""; | |
} | |
</script> | |
</head> | |
<body onload="displayCommentsOnLoad()"> | |
<h3>This is a great blog post</h3> | |
<div id="content"> | |
I like to write about technology because I want to get on the | |
front page of hacker news. | |
</div> | |
<hr> | |
<div id="comments"></div> | |
<hr> | |
Add comment: | |
<input id="new_comment"><input type="submit" onClick="addComment()"> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment