[英]Mongoose - No matching document found (ForEach)
我是NodeJS和Mongoose的新手,這可能是一個重復的問題,所以請不要負面答復。 我試圖找到解決方案,但未能解決此錯誤。
基本上,當我嘗試更新數據庫值時會收到此錯誤。 我執行的第一個更新工作正常,但是從第二個更新開始,出現此錯誤。 值會更新,但會立即更新幾個字段,從而導致此錯誤。
這是我的代碼:(並且我已將github鏈接添加到項目中):
User.js(模型)
local: {
...,
education: [{
id: String,
degree: String,
institute: String,
dates: String,
description: String
}],
...
}
router.js
app.put('/put_education/:id', function(req, res) {
var row_id = req.params.id; //get education id from table row
//get the current logged in user
User.findById(req.user._id, function (err, doc) {
if (err) {
console.log('no entry found');
}
//match the table row id with the id in users education model
doc.local.education.forEach(function (education, index) {
console.log(education.id + " " + row_id);
//if rows match, replace the database document with values from client
if(education.id === row_id){
doc.local.education[index] = req.body;
doc.save(function (err) {
if (err) {
console.log(err);
} else {
res.send("Success");
}
});
}
});
});
});
我添加了一個console.log來查看循環的運行,下圖顯示了第一次迭代的效果,但對於下一次迭代卻表現得很奇怪:
我本來想在id匹配后中斷循環,但是foreach循環沒有中斷功能,我將其更改為普通的for循環,但它仍然給我同樣的錯誤。 所以我不認為打破循環是一個答案。
GitHub: https : //github.coventry.ac.uk/salmanfazal01/304CEM-Back-End
如果爆發迭代是您的問題,那么為什么不使用帶有break語句的簡單for循環。
let eduArray = doc.local.education;
for(i=0;i<eduArray.length;i++) {
if(eduArray[i]["id"] == row_id) {
// do your logic
break;
}
}
因為您是第一次毫無問題地更新教育,然后問題隨后出現,我懷疑您錯誤地更新了教育,請看一下您編寫的以下代碼行:
doc.local.education [index] = req.body;
在這里,我看到您正在將請求正文中的任何內容分配給教育,但是您是否檢查了req.body中實際上是什么數據?
嘗試登錄請求正文以查看您實際分配給該教育的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.