I'm using mongoose to create a new member entry in the database after checking if the member already exists in the database. I need to return a response if the member already exists, otherwise continue inserting the new member. Here is the code:
createNewMember = (req, res, next) => { Member.findOne({email: email}).exec() .then((members) => { if(members == null || members.length==0) { //Create new member object return newMember.save() // 1 --> return promise } else { res.status(409).json({message: "Member already exists"}) // 2 --> I want to return } }) .then((result) => { if(res.statusCode === 409) return res; // 3 --> I added this hack to solve the problem return res.status(201).json({message: "Member has been created"}); // 4 --> then block of newMember.save() }) .catch(err => { // Handle the error and return an error response })
What I want is that if the process reaches point 2, the promise chain is broken, but the second then block is still called. Point 3 is a check I added to prevent the second then block from being executed, but I don't think this is the best way to handle it. I believe this is a common scenario, is there a better way?
There is no way to break the promise chain except throwing your own error and jumping to the catch block. However, you don't want to use an error like that, because the situation itself is not an error, but just a specific logical situation (the member already exists). I recommend thinking of your .then() as layers of cake with different concerns, like this: