Currently, I am delving into Promise chaining and experimenting with some code involving express and mongoose in a node environment. Below is the snippet of code that I am working on:
const register = (req, res, next) => {
User.findOne(req.params.email).exec().then(user => {
if (user) {
return res.status(409).json({ error: 409 });
}
return User.create(req.body);
}).then(user => {
const token = jwt.sign({ sub: user._id }, 'test-secret');
return res.status(200).json({ token });
}).catch(err => {
return next(err);
});
};
This piece of code simplifies the process of registering a user and providing them with a token. My objective is to first check if the user already exists, and if not, proceed with the registration.
Line 6 seems incorrect as it does not appear to be returning any Promise, causing the code execution to continue after line 4. I aim to steer clear of callback hell, so I am seeking guidance on how to achieve this. Thank you!