1 | initial version |
Here are the steps to gather user input and store the data in a MongoDB collection within a .mongodb file using JavaScript:
Install the MongoDB Node.js driver using npm in your project folder by running the command: npm install mongodb
Create a connection to the MongoDB database:
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<cluster>/<dbname>?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("<dbname>").collection("<collectionname>");
// perform actions on the collection object
client.close();
});
Replace the username
, password
, cluster
, dbname
, and collectionname
with your database credentials.
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name"><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email"><br><br>
<input type="submit" value="Submit" onclick="submitForm(event)">
</form>
function submitForm(event) {
event.preventDefault(); // prevent the form from refreshing the page
const name = document.getElementById("name").value;
const email = document.getElementById("email").value;
// create a new document to insert into the collection
const newDoc = {
name: name,
email: email
};
// insert the document into the collection
collection.insertOne(newDoc, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
});
}
submitForm()
function when the form is submitted by clicking the "Submit" button.This will gather the user input from the form, create a new document to insert into the MongoDB collection, and insert the document into the collection. The data will be stored in the .mongodb file for future use.