Utilizing Mongoose promises with Node.js can lead to quicker response times

In my current project using the MERN stack, I have noticed that certain functions in the server-side related to fetching or saving data in MongoDB involve a lot of callbacks. To prevent getting stuck in callback hell, I am exploring a promises-based approach. However, I have run into an issue with this promised-based solution. There is a specific condition where I need to either continue executing the code or return a response and halt.

  const mId = req.body.mId;
  const cId = req.body.cId;
  const lId = req.body.lId;
  LP.findOne({
    'userId': lId,
    'courseId': cId
  })
  .then( lP => {
      return lP.materials;
  })
  .then( materials => {
    if( materials.includes(mId) ) {
      console.log('A')
      return res.json({'status': 'success'})
    }
    else {
      materials.push(materialId)
      return LP.findOneAndUpdate({
        'userId': learnerId,
        'courseId': courseId
      }, {
        $set: { materials: materials}
      }, {
        new: true
      })
    }
  })
  .then( update => {
    console.log('B')
    return res.json({ 'status': 'success' })
  })
  .catch( err => {
    return res.json({ 'status': 'fail' })
  })

In the above code snippet, after A is printed, B is also displayed, triggering further execution which results in the error "Cannot set headers after they are sent to the client." While I understand this behavior is typical of promises, I am looking for possible solutions to avoid this problem. How can I return a response early on without continuing the code execution?

Thank you.

Answer №1

Make sure to break the chain:

  const materialId = req.body.materialId;
  const courseId = req.body.courseId;
  const learnerId = req.body.learnerId;
  LP.findOne({
    'userId': learnerId,
    'courseId': courseId
  })
  .then( lp => {
      return lp.materials;
  })
  .then( materials => {
    if( materials.includes(materialId) ) {
      console.log('A')
      res.json({'status': 'success'})
    }
    else {
      materials.push(materialId)
      return LP.findOneAndUpdate({
        'userId': learnerId,
        'courseId': courseId
      }, {
        $set: { materials: materials}
      }, {
        new: true
      })
    }
  })
  .then( update => {
    console.log('B')
    res.json({ 'status': 'success' })
  })
  .catch( err => {
    res.json({ 'status': 'fail' })
  })

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

Expanding list selection with jQuery_hover effect

I have devised the following code. HTML <ul class="treatment-menu"> <li>Menu always visible</li> <ul class="nav-child"> <li>Hidden sub menu</li> </ul> </ul> Hover function $(&a ...

Is there a way to nest arrays within arrays in JavaScript?

Array ( [0] => Array ( [contactId] => 5 [companyId] => 54 [personName] => Awais [contactNo] => 0321-1111111 [contactType] => Partner ) ) data[0].personName I ...

How can I extract the URL from the event listener in Cordova's in-app browser event and then automatically close it once a specific URL is reached?

In my journey with ionic version 1 (just starting out with ionic & angularjs), I encountered an issue while trying to close the in app browser upon reaching a specific URL. The problem arises from the fact that the event triggered on "loadstart" is o ...

Experiencing incorrect outcome when using the Number.isInteger() function in JavaScript

I have been experimenting with the Number.isInteger() method on the Chrome console. After running a for loop and checking the result using console.log(arr);, I noticed that the array only contains a single value of 1, like this: [1]; var arr = [1, 2, 3, ...

How to use jQuery to hide radio buttons that are not checked when clicking a submit

Looking to dynamically hide all unchecked radio buttons and their labels until a submit button is clicked, displaying only the checked radio button. <form method="post"> <input type="radio" name="radiobtn"> <label for="first">Fir ...

Using arrays as props in React with Typescript

In my code, I have a Navbar component that contains a NavDropdown component. I want to pass an array as a prop to the NavDropdown component in order to display its dropdown items. The array will be structured like this: DropDownItems: [ { ...

Traversing JSON data in a recursive manner without definite knowledge of its size or nesting levels

Currently, I'm working on a chrome app that utilizes local storage. The backend returns JSON data which I then save locally and encrypt all the items within the JSON. I have multiple sets of JSON with different encryption functions for each set. I at ...

Encountering the 'data is null' error when making a Twitter API request, yet the data is successfully displayed in the browser

I am attempting to show the number of followers for a Twitter account, but when I connect to the API using this code: $.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) { console.log ...

Using http-proxy-middleware in a React application for browser proxy

I'm having trouble with setting up a proxy in my React app. Scenario: I have two React apps, one running on localhost:3000 and the other on localhost:3001. What I want to achieve is that when I click on: <a href="/app2"> <button> ...

The Content-Type header is missing in the Ajax request for json

In my PHP code, I generate valid JSON and set the content-type header to application/json in my development environment. However, when I deploy this code to an embedded web server, it functions properly but is unable to send the appropriate content-type he ...

Perform a bulk insert/update operation on multiple documents in MongoDB using PHP

My goal is to import data from an external source into mongodb using php. Each row in the external data represents a mongodb document, and each row has a unique identifier known as uid. Currently, I am attempting the following approach: I would like to in ...

Retrieve the reference to the plugin object from the element where the plugin is currently active

Take a look at the code below. I've implemented a jquery plugin called myPlugin to modify the UI of #targetElement. var myPluginVar = $('#targetElement').myPlugin(); I have created a button and attached a click event listener to it. $(&ap ...

Is there a way to retrieve the id of every post on my page?

Is it possible to send multiple post ids in JavaScript? I have successfully sent the first post id, but now I need to figure out how to send each individual post id. When inspecting the elements, I see something like this: <div data-id="post_1">< ...

Highlighted keyword: Unusual mouse movements

I am utilizing the Summernote plugin from Summernote to craft an aesthetically pleasing textarea, and adding the Mark.js plugin from Mark.js to highlight a specified keyword (such as foo) within that textarea. This is the HTML code I have: <div id="te ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

Verify whether the input is currently being focused on

My current issue involves an input field that requires a minimum number of characters. If a user begins typing in the field but then switches to another without meeting the character requirement, I would like to change the text color to red. I attempted u ...

Updating the content of a list item on the fly using React

After spending all day on this, I am feeling a bit frazzled. Trying to achieve what would take 20 seconds in JQuery has proven to be quite the challenge in React ¯\_(ツ)_/¯ In my application, tags are ranked by importance from 1 to 9. Simple enoug ...

Having trouble establishing a connection to MongoDB Compass using the specified connection string

I've set up a cluster and now I'd like to connect to it using MongoDB Compass. When I try to connect via Connect -> I have MongoDB Compass, I receive the connection string below: mongodb+srv://myname:<password>@myname.nauqp.mongodb.net/ ...

Align the image in the middle using JavaScript for Firebase

I am struggling to display the center of an image within a circle-shaped <img> tag with a border-radius of 50%. The issue arises when trying to display an image fetched from Firebase storage, rather than from a URL. In attempt to solve this problem, ...

The jQuery .val() function does not function properly when using 'this'

This is an example with a textarea: <textarea id='ta' onkeydown='down(this)'></textarea> and here is the accompanying JavaScript code: <script> function down(input) { alert(input.val()); // not functioning ...