[英]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.