Home > Back-end >  I have problem structuring mongoose methods
I have problem structuring mongoose methods

Time:10-22

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?

CodePudding user response:

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
      })

    }
  );
});

CodePudding user response:

Solution 1

You can put Client.create() part inside the callback of the Client.findOne(), and execute it if there is no error.


Solution 2

Don't use callbacks, but async/await instead, which will make your code much more readable.

Note: I know you wrote you don't want async/await, but I am adding it as a second solution so you can compare the code readability.

const someFunction = async (req, res, next) => {
  try {
    const client = await Client.findOne({ remarks }); 

    if(client) return res.status(400).json({ success: false });

    const new_client = await Client.create({ fullname, email, telephone, country, city, remarks });

    return res.status(200).json({ success: true, client: new_client }); 
  } catch (error) {
    return res.status(400).json({ success: false });
  }
}
  • Related