I am having a problem using callback function in mongoose.
Client.findOne({remarks}, (error, docs) => {
if(error){
//logging error to DB
return next(error)
}
if(docs){
return next(new ErrorResponse(IdenticalRemarksError, 400))
}
})
Client.create(
{ fullname, email, telephone, country, city, remarks },
(error, docs) => {
if(error){
return next(error)
}
res.status(201).json({
success: true,
data: docs
})
}
);
The return inside Client.findOne() callback does not end the entire register controler ie Client.create() still runs. I know this is because the return is local to the Client.findOne().
What is the best way of restructuring this in such a way that the return statement inside if(docs){} in Client.findOne() will end the entire controller function without imploying async await? ie The client wont be created if a remark is found in the findOne() method?
Once try with the following code:
Client.findOne({ remarks }, (error, docs) => {
if (error) {
//logging error to DB
return next(error);
}
if (docs) {
return next(new ErrorResponse(IdenticalRemarksError, 400));
}
Client.create(
{ fullname, email, telephone, country, city, remarks },
(error, docs) => {
if (error) {
return next(error);
}
res.status(201).json({
success: true,
data: docs
})
}
);
});