Prevent the execution of a post request function depending on the promise result?

When I handle a POST request in express, I am required to retrieve data from a mongoDB cluster and then respond accordingly based on the retrieved response.

app.post('/api/persons', (req, res) => {
  const data = req.body;

  if (!data.name || !data.number) {
    return res.status(400).json({
      error: 'Name or Number missing',
    });
  }

  const newName = data.name;
  
  Person.find({ name: newName }).then((result) => {
    if (result.length !== 0) {
      return res.status(409).json({
        error: 'Name must be unique',
      });
    }
  });

  const record = new Person({
    name: data.name,
    number: data.number,
  });

  record.save().then((savedRecord) => {
    res.json(savedRecord);
  });
});

Person represents a model in mongoDB

The Person.find method checks the value and returns a boolean. Currently, there are two issues that I need assistance with:

  1. Even after returning a value in the function following the .find call, the process continues and the value gets saved using the record.save() below.

  2. Despite the value being non-existent, the error message Name must be unique is displayed. // Solved it by replacing .exist() with .find()

Is there a way to resolve this without placing the record.save() inside the find promise? I prefer having the .find call within its own function. How can I achieve this?

Thank you

Answer №1

To improve code organization, you can create a separate function called findPerson which will execute Person.find and accept newName, foundCallback, and notFoundCallback as parameters. Take a look at the following code snippet.

const findPerson = (newName, foundCallback, notFoundCallback) => {
    Person.find({ name: newName }).then((results) => {
        if (results.length !== 0) {
            foundCallback();
        } else {
            notFoundCallback();
        }
    });
}

app.post('/api/persons', (req, res) => {
    const data = req.body;

    if (!data.name || !data.number) {
        return res.status(400).json({
            error: 'Name or Number missing',
        });
    }

    const newName = data.name;

    findPerson(
        newName,
        () => res.status(409).json({ error: 'Name must be unique' }),
        () => {
            const newPerson = new Person({
                name: data.name,
                number: data.number,
            });

            newPerson.save().then((savedPerson) => {
                res.json(savedPerson);
            });
        }
    );
});

If you prefer using promises, you can refactor the solution as follows:

const checkUniquePerson = (newName) => {
    return new Promise((resolve, reject) => {
        Person.find({ name: newName }).then((results) => {
            if (results.length !== 0) {
                reject();
            } else {
                resolve();
            }
        });
    });
}

app.post('/api/persons', (req, res) => {
    const data = req.body;

    if (!data.name || !data.number) {
        return res.status(400).json({
            error: 'Name or Number missing',
        });
    }

    const newName = data.name;

    checkUniquePerson(newName).then(() => {
        const newPerson = new Person({
            name: data.name,
            number: data.number,
        });

        newPerson.save().then((savedPerson) => {
            res.json(savedPerson);
        });
    }).catch(() => {
        res.status(409).json({ error: 'Name must be unique' })
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps can I take to troubleshoot and fix the height of a div/span element?

Here is my HTML code: <div> <span style="display: inline-block;height:20px">20</span> <span style="display: inline-block;"><img src="img/ex.png"/></span> </div> The image I have in the second span is sized at ...

Vue.js error: Unable to locate requested resources

Recently, I've been encountering a curious issue when trying to access a specific component in my application. When I manually type the URL http://localhost:8080/detailed-support/start into the browser, the content loads without error. However, none o ...

Tips for interpreting the JSON data returned by a Node server in Angular

When trying to implement a login form in my Angular frontend, I encountered an issue with reading the JSON object returned from my node.js server. Despite following the correct steps, the console displays "undefined" as if it cannot recognize the format. ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

Multer and Express encounter issues when trying to read FormData sent from a React Native client, but have no problem reading and saving the data when using

Whenever I upload an image to my node/express server using multer, the image gets saved in the "uploads" folder successfully. Here's the server-side code along with the Postman request: server.js const express = require("express"); const app = expres ...

The connection between two arrays remains intact even after using the .push() method in JavaScript or Vue.js

I need help setting up two arrays containing dates. The first array should have the dates in string format, while the second array should contain the same dates but as date objects. methods: { test() { let employments = [ { begin: ...

What sets returning a promise from async or a regular function apart?

I have been pondering whether the async keyword is redundant when simply returning a promise for some time now. Let's take a look at this example: async function thePromise() { const v = await Inner(); return v+1; } async function wrapper() ...

How to programmatically close a colorbox using an ASP.NET form's Submit button within an iframe

I've looked at other similar questions, but I just can't seem to make this work. I want to close the colorbox iframe when a .NET Button form within the iframe is clicked. <script type="text/javascript"> $(document).ready(function() { ...

load a file with a client-side variable

Is there a way to load a file inside a container while utilizing an argument to fetch data from the database initially? $('#story').load('test.php'); test.php $st = $db->query("select * from users where id = " . $id); ... proce ...

Performing an AngularJS $http POST request with a combination of JSON parameter and query string

I'm currently trying to write an AJAX call using Angular's $http object in order to send a post request with JSON in the body and a query string appended to the URL. Despite going through the documentation for $http, looking for solutions on SO, ...

Translate CSS into JavaScript while maintaining selector understanding

I am interested in developing a tool that can read a .css file and generate a function that will accept an array of class names as input and output the corresponding styles for an element with those classes, represented as a JavaScript object. This tool wo ...

Utilizing the await feature in Express.js in conjunction with Passport authentication

Having trouble integrating mySQL into passport.js for user authentication in express.js. I'm struggling to properly implement the await functionality. Server.js: initializePassport( passport, function(email) { pool.getConnection(function(err, ...

What is the appropriate way to notify Gulp when a task has been completed?

I have been working on developing a gulp plugin that counts the number of files in the stream. Taking inspiration from a helpful thread on Stack Overflow (source), I started implementing the following code: function count() { var count = 0; function ...

The console is not displaying the data from the useForm

I am working on a project to create a Gmail clone. I have implemented the useForm library for data validation. However, when I input data into the form and try to print it to the console, nothing is being displayed. const onSubmit = (data) => { ...

What is the best method for dividing strings in javascript?

After invoking a JavaScript function, I received the following results: (1, 00), (2, 10), (3, 01), (4, 11) I am looking to store this data in an array or JSON format like this: [{id:1, number: 00},{id:2, number: 10},{id:3, number: 01},{id:4, number: 11} ...

Error functions in Angular HTTP Interceptor are not being triggered

I followed the example code for an interceptor from the Angular HTTP documentation, but I am having trouble getting the "requestError" and "responseError" functions to trigger. The "request" and "response" functions are working as expected. myApp.config([ ...

Modifying an object's value before pushing it into an array in JavaScript

I've been struggling to find the right keyword to search for my issue. I've spent hours trying to figure out what's wrong, but it seems like a simple case of pushing an object into an array. The problem arises when I try to log the values of ...

Ways to enable JavaScript code to accept input from both a text field and a text

I have a JavaScript code that allows users to input text and choose to make it bold, italicized, or underlined. For example, if the user checks the bold option, the text will appear in bold format. Here is the JavaScript code I am using: $('input[n ...

The size of my React Native app is significantly larger than expected once installed

I recently developed a React Native app, and while the release APK size is only 28 MBs, I was shocked to see that the storage size is a whopping 62 MBs. I am desperately looking for a solution as I need to deliver this project soon. Please help me resolv ...