【发布时间】:2018-07-06 12:36:19
【问题描述】:
我正在练习使用 MongoDB 构建一个简单的 Express 应用程序。我创建了一个端点,它将按名称搜索用户,然后使用数据库中存储的数据呈现页面。当找不到配置文件时,我尝试集成一些代码来处理,但这会破坏应用程序。
此代码有效 - 个人资料页面按预期呈现:
app.get('/profiles/:name', (req, res) => {
// calling the model
Profile
.find({ "name.first": req.params.name })
.then(profileArray => {
let profile = profileArray[0];
let img =
`<img class="ui rounded image" src="http://api.adorable.io/avatar/250/${profile.name.first}${profile.age}" />`
res.render('profile', { profile, img });
})
.catch(error => {
if (error.reason === "ValidationError") {
console.log(error);
let response404 = error;
res.render('add', { response404 });
}
else {
console.log(error);
res.render('add');
}
});
});
但是当我在 find() 和 then() 之间集成以下代码时 - 它会破坏应用程序:
.count()
.then(count => {
if (count < 1) {
return Promise.reject({
code: 404,
reason: "ValidationError",
message: "Profile not found. Please create a profile."
})
};
})
以下是导致崩溃的带有 sn-p 的完整端点代码:
app.get('/profiles/:name', (req, res) => {
// calling the model
Profile
.find({ "name.first": req.params.name })
.count()
.then(count => {
if (count < 1) {
return Promise.reject({
code: 404,
reason: "ValidationError",
message: "Profile not found. Please create a profile."
})
};
})
.then(profileArray => {
let profile = profileArray[0];
let img =
`<img class="ui rounded image" src="http://api.adorable.io/avatar/250/${profile.name.first}${profile.age}" />`
res.render('profile', { profile, img });
})
.catch(error => {
if (error.reason === "ValidationError") {
console.log(error);
let response404 = error;
res.render('add', { response404 });
}
else {
console.log(error);
res.render('add');
}
});
});
它会抛出这个错误:“TypeError: Cannot read property '0' of undefined”。
它指的是第二个then() 我试图访问从find() 返回的数组。
find() 的数据似乎丢失了。如何通过count() 和第一个then() 传递找到的文档?
有一点需要注意。当我集成错误处理代码时,我拒绝了承诺并使用表单呈现一个新页面。该部分有效,但是当尝试使用数据库中确实存在的名称呈现页面时,它会中断。我在链的某个地方丢失了数据。如果您需要任何澄清,请告诉我。谢谢。
【问题讨论】:
-
尝试检查count变量是否从promise中得到正确的值
-
是的,它得到了预期值。我在条件之前和内部控制台记录计数。找到配置文件时,它永远不会进入 if 条件,这是预期的。因此,如果找到配置文件,那么我该如何继续?它似乎停在那里而不是继续到链中的下一个承诺。
-
当你做'find'然后'count'时,你会丢失'find'的结果,见这个:stackoverflow.com/questions/35443821/…
-
@zb22 很好的发现。我给了你一个赞成票。但是,已经接受了答案。感谢您的帮助。
标签: node.js mongodb express mongoose