Error: The query has already been processed:

I'm encountering an issue while attempting to update the document. The error message indicates that the query has already been executed.

MongooseError: Query was already executed: footballs.updateOne({ date: 'January 4' }, {})

app.post('/api/bookslot', async (req, res) => {
  console.log(req.body);
  try {
    const token = req.headers['x-access-token'];
    const decoded = jwt.verify(token, 'secret123');
    const email = decoded.email;
    const user = await UserModel.findOne({ email: email });

    let sportname = req.body.selectedSport.toLowerCase();
    const time = req.body.slotTime;
    const seats = req.body.availableSeats - 1;

    if (!sportname.endsWith('s')) {
      sportname = sportname.concat('s');
    }
    const NewSlotModel = mongoose.model(sportname, slotSchema);
    var update = {};
    update[time] = seats - 1;
    console.log(update);
    const a = await NewSlotModel.updateOne(
      { date: req.body.slotDate },
      { $set: update },
      function (err, success) {
        if (err) return handleError(err);
      }
    );

    return res.json({ status: 'ok' });
  } catch (e) {
    console.log(e);
    res.json({ status: 'error' });
  }
});

What could be my mistake in this code?

Answer №1

Your current code is causing mongoose to throw an error due to a conflict between async/await and callbacks. The specific error message you are encountering is:

Query was already executed

In Mongoose version 6, duplicate queries are not allowed.

Mongoose now prohibits executing the same query object more than once. If you attempt this, you will receive a Query was already executed error. This behavior usually indicates a mix of callbacks and promises. However, if you need to run the same query again, you can use Query#clone() to duplicate the query and re-run it. Refer to gh-7398 for details.

Learn More About Duplicate Query Execution

To resolve this issue, simply remove the third argument from the await statement.

NewSlotModel.updateOne

This means updating your code as follows:

const a = await NewSlotModel.updateOne(
  { date: req.body.slotDate },
  { $set: update }
);

Answer №2

Mongoose version 6 no longer supports callbacks, please refer to the image provided.

const productCount = await Product.countDocuments((count) => count)  AVOID

const productCount = await Product.countDocuments(); RECOMMENDED

https://i.sstatic.net/3r8WP.png

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

The power of MobX lies in its ability to provide a deep

I'm currently delving into the concept of deep observability in MobX. I'm looking for insights on why the autorun function is not being triggered every time I call setCommentCountForPost in the code snippet below. Can someone point me in the rig ...

Perform a fetch request within a map function or loop

I'm currently working on iterating over an array of objects. Depending on the content of some of those objects, I need to execute a fetch function and wait for the result before updating the new array. Below is my JavaScript code: const allPosts = ...

Is there a distinction between "muted" and "volume = 0.0"? Event listeners handle them in separate ways

I am a newcomer to coding and have encountered an issue that has me stumped. I am working on developing a small media player intended for use with the athletes I coach. The concept is to require them to listen to my commentary while watching game footage. ...

JQuery form serialize not triggering in Internet Explorer

I've encountered an issue with a form inside a jQuery dialog that is not submitting properly in Internet Explorer. The form functions correctly in Chrome and Firefox, sending data to my MVC controller without any issues. However, when using IE, it on ...

Is it feasible to retrieve two sets of AWS credentials from a JSON file?

  I am working on developing a node.js express application and I require the ability to access two different sets of credentials depending on the user’s context. Currently, I have configured the app to retrieve one set of credentials from a specific co ...

express not resolving async callback

Exploring the concept of promises further, I decided to create a simple async delay function that incorporates a timeout feature: const app = express(); function timeout(duration) { return new Promise((resolve, reject) => setTimeout(() => { ...

Unexpected behavior involving the onchange event, input validation, and the enter key

One challenge I encountered was implementing validation for a date input field in a form. The requirement was to only allow dates starting from today up to a maximum of 3 years in the future. If a valid date is entered, a modal should appear; otherwise, an ...

What are the best methods for concealing a ng-repeat element with AngularJS?

.controller('CouponsCtrl', ['$scope', '$http', '$window', '$location', '$ionicPopup','$ionicLoading', function($scope, $http, $window, $location, $ionicPopup,$ionicLoading) { ...

Is it not possible to call a function directly from the controller in AngularJS?

I have been trying to update a clock time displayed in an h1 element. My approach was to update the time by calling a function using setInterval, but I faced difficulties in making the call. Eventually, I discovered that using the apply method provided a s ...

Issues with AngularJS <a> tag hyperlinks not functioning as expected

After performing a search, I have an array of objects that needs to be displayed on the template using ng-repeat. The issue arises when constructing the URL for each item in the array – although the ng-href and href attributes are correct, clicking on th ...

Inquiry on integrating Spotify with Axios for my debut solo project (beginner inquiry)

I have a question regarding my first solo project in React. I started learning code in September and I'm facing an issue while making a POST request to the Spotify API to retrieve an access token: Despite following the recommended 'Content-Type& ...

Stopping the parent onclick event from propagating to a child element within a bootstrap modal

I am currently working with angularjs and bootstrap, incorporating nested onclick events using Angular's ng-click in various HTML elements. One is located in a table header to display different sort icons and execute the sorting logic when the header ...

What is the best way to securely transfer data from a Node/Express server to the client using JavaScript, ensuring sanitized HTML and preventing cross-site scripting (X

What is the best method to securely pass data from an Express backend to a client-side JavaScript in order to render it in the DOM using client-side rendering, while also allowing sanitized whitelist HTML and preventing XSS attacks? For example, if the No ...

Struggling to delete a specific item by its ID from MongoDB within a Next.js application

Currently, I am building a todo app in nextjs to enhance my skills. However, I'm encountering some difficulties in deleting single todos from the database using the deleteOne function. Below is the frontend call: async function deleteTodo(id) { a ...

When implementing protractor spyOn() with jQuery's ajax() function, an error is triggered stating 'ajax() method is non-existent'

I am currently testing the functionality of using AJAX to submit a form. Below is the Protractor code for the test: describe('login.php', function() { it("should use ajax on submit", function() { browser.get('/login.php'); spyOn($ ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

Error message: ParseError: Received an unexpected character '<' while running tests using AVA

Initially encountering an issue within the project built on nuxt, I attempted to resolve it by creating a new project using vue-cli and re-installing AVA via npm. However, this did not have any effect on the problem at hand. Upon researching, I came across ...

What is another option for toggling in jQuery?

After deprecating the toggle method, I found a new way to toggle div: $("#syndicates_showmore").on("click", function () { if (!clicked) { $('#syndicates').fadeTo('slow', 0.3, function () { $(this).css( ...

Jasmine (mocha) "it" tests organized in a nested format

Recently, I set out to test the consecutive create/delete operations of items in mongoDB using mongoose. However, I encountered a challenge - the creation process is asynchronous and returns the ID of the created item in a callback function. This ID is cru ...

Steps for embedding a custom function in a switch statement

I am attempting to run a switch statement based on the argument provided to the function below. I have been trying to call different functions depending on the argument passed. However, I encountered an Uncaught ReferenceError in the beginning of the .js f ...