Guidelines for incorporating a MongoDB sorting feature within an express router

Struggling to incorporate one of MongoDB's built-in sorting algorithms into a Model.find()? It seems easy to understand and apply it in the mongo command line, but implementing it within your code remains a challenge.

While the existing code functions perfectly and retrieves the desired values, you now aim to introduce the stored sort from mySort to organize the data being fetched.

const express = require('express'),
    router = express.Router(),
    House = require('../models/house'),
    Event = require('../models/event');

router.get('/', function(req, res){

    var mySort = {totalPoints: -1};

    House.find({}, function(err, houses){
        if(err){
            console.log(err);
            res.redirect('/error');
        } else {
            res.render('houses/index', {pageTitle: 'Houses', houses: houses});
        }
    });
});

module.exports = router;

You anticipate that the houses will be arranged in descending order based on the values of totalPoints.

Answer №1

If you're looking for the right syntax, consider this example:

Apartment
   .find()
   .sort("-overallRating") // or { "overallRating" : -1 }
   .exec( apartments => ... )

Alternatively, you can use async/await like so:

const apartments = await Apartment.find().sort("-overallRating")

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

Registering dynamic modules within a nested module structure - Vuex

As stated in the Vuex documentation, a nested module can be dynamically registered like this: store.registerModule(['nested', 'myModule'], { // ... }) To access this state, you would use store.state.nested.myModule My question is h ...

What is the best way to include more than two conditions in my code? For example, using if, if, else

<!DOCTYPE html> <html> <head> <title>efgh</title> </head> <body> <p id="result"></p> <button onclick="verifyInput()">check input</button> <script> function ver ...

JavaScript still mentions a class that no longer exists

One of my elements has a class of .collapsed. When this element is clicked, a jQuery function is triggered to remove the .collapsed class and add the .expanded class instead. Even after the .collapsed class is removed, the function I have created continue ...

Attempting to create a button that will only appear for items with a defined value for a specific variable

I am currently facing an issue with a template that needs proper population. The store locator on my website lists pharmacies and displays their relevant information (phone number, address, hours of operation) along with three buttons (view store, view fl ...

Using ReactJS to Retrieve Input Value from Prompt Box and Save to Database

I'm currently developing a MERN application and I need to allow users to edit the food name by clicking on the prompt box that pops up when they click the Edit button. The approach I was following can be found in this link: [https://stackoverflow.com ...

Is it possible to send an ajax request within another ajax request?

I'm facing an issue with a php file that is sending an ajax request to another file located on a different domain name. The receiving parser then processes the information and sends it via ajax to yet another php file where the final action is carried ...

Unauthorized access detected during ajax request triggered by onpaste event

Recently, I encountered an issue with my asp.net mvc website where an ajax call to the server stopped working in IE 11, despite previously working fine in IE 8. The error message pointed to an access denied exception in jQuery 1.7.1 at h.open(c.type,c.url, ...

Creating distinct identifiers for table cells utilizing the map function

Is there a way to assign a unique id to each MenuItem using the map() function nested within another one? <table className={classes.table}> <thead> <tr> <td /> {sit.sit.map(sit => ( <td className={ ...

What could be causing jQuery to fail to detect changes in the HTML code?

Whenever I trigger an Ajax request and update an attribute value, the DOM reflects the changes as expected. However, upon clicking the button again, the console displays the old attribute value. It seems like the markup isn't recognizing the change an ...

The fetch request became unresponsive and failed to return any data

A ComboBox.js component is interacting with a PHP server. The issue arises in the componentDidMount method, where a fetch call triggers, causing the browser to stall at "http://localhost:3000/search?code=b12a2302e2d0f2b22143b7b4e0472901b2c1b9a8&state=x ...

Make sure the express app is active before initiating mocha tests

I recently created an API for a Couchbase database using Express and Node.js. Interestingly, during my testing phase, some tests failed due to the server not being fully operational. After doing some research, I came across a helpful solution outlined on t ...

Transfer an URL parameter from the URL to the server using PHP or JavaScript

My goal here is to pass the URL as a parameter named "web_url". The code snippet above shows an AJAX request being sent to a PHP server on the backend. On the PHP side, I'm attempting to capture this parameter using: $web_url = $_GET["web_url"]; H ...

Plumage reaching out to personalized API function

To set up my API, I typically write something like the following: class MyFeathersApi { feathersClient: any; accountsAPI: any; productsAPI: any; constructor(app) { var port: number = app.get('port'); this.accountsAPI = app.serv ...

Unable to modify document value in MongoDB using Node.js

Currently, I am attempting to fetch the value of a field form that is being sent to a subroute and utilize it to update a database collection. My ability to retrieve the form value and manipulate it is working fine; however, I encounter an issue when I sol ...

The combination of Javascript and CSS allows for interactive and visually

I'm currently working on a project where I had to create a simulated weather page using only Javascript. However, I am struggling with the overall layout and have a few questions that I hope someone can help me with: Despite trying various methods ...

Currently, I am utilizing Angular 2 to extract the name of a restaurant from a drop-down menu as soon as I input at least two characters

I am currently utilizing Angular 2 and I am trying to retrieve the names of all restaurants from a dropdown menu. Currently, when I click on the text field, it displays all the results, but I would like it to only show results after I have entered at least ...

Searching for a field's value and projecting based on a condition in MongoDB - A comprehensive guide

In this query, we are trying to project examDetails while ensuring that values in userExamDetails are not included. However, it seems that the $eq condition is not functioning as expected. db.getCollection('collectionOne').aggregate([ {'$ma ...

Tips for managing errors when working with deserializeUser in Express Passport

Is there a way to forward an error from passport.deserializeUser to my error handling middleware, and then execute req.logout to log out the user? passport.deserializeUser((id, done) => { Family.findById(id).then(family => { done(null, famil ...

Steps for implementing authentication check with Express middleware before uploading a file using Multer in my route

Currently focusing on my backend development using node.js and express, I recently started incorporating multer for file uploads. I am trying to implement a validation process to check if the user has a valid token before allowing them to upload a file. H ...

Tips for accessing the next sequential tag that is similar in HTML with the help of jQuery

I have generated the following HTML code from some plugins. <div class="parent"> <span>item1</span> <input type="hidden"></input> <span>item2</span> <span class="active">item3</span> <inpu ...