Error: TypeError: Cannot read property 'catch' of undefined when trying to register user for website node.js
15,281
If newUser.save
can return a promise, you definitely shouldn’t be passing a callback to it, or even using the Promise
constructor at all. If you really want to reject with strings, the way to implement that would be by transforming rejections from newUser.save()
with .catch
into new rejections by returning them, and returning the resulting promise from registerUser
:
module.exports.registerUser = function (userData) {
if (userData.password != userData.password2) {
return Promise.reject("Passwords do not match");
}
let newUser = new User(userData);
return newUser.save().catch((err) => {
if (err.code == 11000) {
return Promise.reject('User Name already taken');
}
else {
return Promise.reject('There was an error creating the user: ${err}');
}
});
};
Related videos on Youtube
Comments
-
Jasper French almost 2 years
I seem to have messed up one of my promises (I think) in a javascript function that is supposed to register a user. I have included the post request and the actual function itself.
app.post("/register", (req, res) => { dataServiceAuth.registerUser(req.body).then(() => { res.render("register", {successMessage: "User created"}); }).catch((err) => { res.render("register", {errorMessage: err, user: req.body.user}); }); }); module.exports.registerUser = function (userData) { return new Promise(function (resolve, reject) { if (userData.password != userData.password2) { reject("Passwords do not match"); } else { let newUser = new User(userData); newUser.save((err) => { resolve(); }).catch((err) => { if (err) { if (err.code == 11000) { reject('User Name already taken'); } else { reject('There was an error creating the user: ${err}'); } } }); } }); };
-
CertainPerformance about 6 yearsSeems like
newUser.save
is not returning somethingcatch
able, butnewUser.save
was not posted in your code. -
traktor about 6 yearsCheck if
newUser.save
is a Node style callback which is passed a falsey value for theerr
parameter when the operation succeeded, or a non-falsey value (includes non zero numbers) if an error occurred.
-
-
Jasper French about 6 yearsAwesome looks fixed everything and it looks a lot cleaner as well.