我正在练习使用 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."
})
};
})
以下是完整的端点代码以及导致崩溃的代码片段:
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:无法读取未定义的属性“0””。
它指的是第二个 then()
,我试图访问从 find()
返回的数组。
来自 find()
的数据似乎丢失了。如何通过 count()
和第一个 then()
传递找到的文档?
有一点需要注意。当我集成错误处理代码时,我拒绝 promise 并使用表单呈现一个新页面。该部分有效,但是当尝试使用数据库中确实存在的名称呈现页面时,它会中断。我在链条上的某个地方丢失了数据。如果您需要澄清任何事情,请告诉我。谢谢。
最佳答案
还有另一种方法可以做到这一点。
Profile.find({ "name.first": req.params.name })
.then((docs) => {
if(docs.length < 1) {
return Promise.reject({
code: 404,
reason: "ValidationError",
message: "Profile not found. Please create a profile."
})
let profile = docs[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');
}
});
});
您可以使用docs.length
获取文档的数量,docs
包含mongoDB返回的数据。这是一种替代方法。
关于node.js - MongoDB - 如何通过find().count()传递数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48473759/