I am trying to create a new document in my firestore database using the REST API with javascript.
I have looked at the documentation for examples but I don't see any when it comes to using the Rest Api in Javascript.
I have constructed it in Postman and it works ok but I just cannot figure it out how to wire this upto a button click event in javascript.
Does anyone have a working example I can learn from please.
CodePudding user response:
Here is an example with fetch, based on the Firestore REST API documentation.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script>
function saveDoc() {
// We first build the Document object
// See https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents#Document
const firebaseDocObj = {
fields: {
name: {
stringValue: 'Magritte',
},
country: {
stringValue: 'Belgium',
},
},
};
fetch(
'https://firestore.googleapis.com/v1/projects/<your-project-id>/databases/(default)/documents/test-collection',
{
method: 'POST',
body: JSON.stringify(firebaseDocObj),
}
)
.then((response) => {
console.log(response);
return response.json();
})
.then((data) => {
alert('Doc created');
console.log('success', data);
})
.catch((error) => {
alert(JSON.stringify(error));
console.log('failed', error);
});
}
</script>
</head>
<body>
<input
id="clickMe"
type="button"
value="Create a doc"
onclick="saveDoc();"
/>
</body>
</html>