Under normal circumstances, I can write the data in the 2 text fields that I created at the beginning and send it to the db, but when I add a button next to the throw to Mongodb button (the button’s function is to add a new text field every time it is clicked), I cannot take the data from the new text fields there and assign Mongodb, can you help?
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<style>
.democlass {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #555;
background-color: #fff;
background-image: none;
border: 1px solid #ccc;
border-radius: 4px;
margin-top: 10px;
margin-bottom: 10px;
}
</style>
<body>
<h1>Posting data to mongo</h1>
<form class="containter" method="post" action="/">
<div class="form-group">
<input class="form-control" name="title">
</div>
<div class="form-group">
<input class="form-control" name="content">
</div>
<button>add mobgodb</button>
</form>
<button type="button" onclick="myFunction()">Click me</button>
<form class="containter" method="post" action="/">
<script>
function myFunction() {
var x = document.createElement("input");
x.setAttribute("type", "text");
x.setAttribute("name", "content2");
x.setAttribute("class", "democlass");
document.querySelector(".form-group").appendChild(x);
const num = document.getElementById('input').value;
console.log(num)
}
</script>
</form>
<script>src = "server.js"</script>
</body>
</html>
js file
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }))
const url = //your mongodb's url;
mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log("Basarili"))
.catch((err) => console.log(err))
const notesSchema = {
title: String,
content: String,
content2: String
}
const Note = mongoose.model("Note", notesSchema);
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
})
app.post("/", function(req, res) {
let newNote = new Note({
title: req.body.title,
content: req.body.content,
content2: req.body.content2
});
newNote.save();
res.redirect('/');
})
app.listen(5500, function(){
console.log("server is running on 5500");
})
if you have 2 text it works but i want add more text field and send all data to database
I create 2 text field and this datas send db
2
Answers
Incorrect word spelling in schema defination
If you want to store all your request body you can use following code