因此,我正在學習Node.js和Express,並使用它來製作一個簡單的Web應用程序,該程序在mongoDB數據庫上執行CRUD操作。我可以成功地將信息插入數據庫並進行更新,但是我似乎無法弄清楚如何更新複選框信息。注意我看着Passing checkbox values to database using JavaScript,它沒有幫助,因爲它在meteor.js使用複選框信息更新MongoDB
在我的EJS文件。這是用戶爲了更新數據庫中的匹配條目而必須插入的信息。爲了簡潔起見,我已經省略了一些表格的元素。
<div id="editForm" hidden>
Enter name of the entry you want to edit?<input type="text" placeholder="full name" id="editItem" name="editItem" required><br>
Full Name<input type="text" placeholder="full name" id="fullName" name="name" required><br>
Age <input type="number" name="age" min="18" max="95" id="age" required><br>
Programming Languages <br> <input type="checkbox" class="p_languages2" name="p_languages2" value="Java" required>Java
<input type="checkbox" name="p_languages2" class="p_languages2" value="C++">C++
<input type="checkbox" name="p_languages2" class="p_languages2" value="Python">Python
<input type="checkbox" name="p_languages2" class="p_languages2" value="Ruby">Ruby
<input type="checkbox" name="p_languages2" class="Jp_languages2" value="JavaScript">JavaScript<br>
Available to start work? <input type="date" id="start_date" name="start_date" required><br>
Life Motto? <input type="text" placeholder="motto" id="motto" name="motto" required><br>
<button onClick='putRequest()' type="submit" id="editEntry">Submit</button>
</div>
function putRequest() {
fetch('/view', {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'editedItem': document.getElementById("editItem").value,
'name': document.getElementById("fullName").value,
'age': document.getElementById("age").value,
//how can I extract the checkboxes?
'start_date': document.getElementById("start_date").value,
'motto': document.getElementById("motto").value
})
})
window.location.reload(true);
這裏是我的要求額外信息。請注意,「p_languages」:req.body.p_languages只是一個佔位符,我知道它不起作用。
app.put('/view', function(req, res) {
console.log("Put is working!");
db.collection('jobs').findAndModify(
{"name": req.body.editedItem },
{},
{$set:
{ "name": req.body.name , "job_title": req.body.job_title, "gender": req.body.gender,
"p_languages": req.body.p_languages, "age": req.body.age, "start_date": req.body.start_date,"motto": req.body.motto }
},
{},
function(err, object) {
if (err){
console.warn(err.message); // returns error if no matching object found
}else{
console.log("Update complete");
}
})
})