I am practicing building a simple Express app with MongoDB. I created an endpoint that will search for a user by name and then render the page with the stored data from the DB. I tried to integrate some code to handle when a profile is not found, but it breaks the app.
This code works- the profile page renders as expected:
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');
}
});
});
But when I integrate the following code- between find()
and then()
- it breaks the app:
.count()
.then(count => {
if (count < 1) {
return Promise.reject({
code: 404,
reason: "ValidationError",
message: "Profile not found. Please create a profile."
})
};
})
Here is the full endpoint code with the snippet that causes the crash:
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');
}
});
});
It throws this error: "TypeError: Cannot read property '0' of undefined".
It is referring to the second then()
where I am trying to access the array returned from find()
.
It seems like the data from find()
is getting lost. How can I pass the found document through count()
and the first then()
?
One thing to note. When I integrate the error handling code, I reject the promise and render a new page with a form. That part works, but when trying to render the page with a name that does exist in the DB it breaks. I'm losing the data somewhere along the chain. Let me know if you need anything clarified. Thanks.