Arranging Data in MeteorJS

I recently delved into MeteorJS, Mongodb, and Iron:router, and wrote a small code to sort a list of websites based on user interactions. Initially, everything worked smoothly, but I encountered an issue with sorting near the end. Specifically, the websites should be sorted by the number of upvotes they have received, as well as the date of creation. Below are the key sections of the code:

//Sorting websites based on userfilter or votes
websites:function(){
  if (Session.get("userFilter")){
    return Websites.find({ createdBy: Session.get("userFilter") }, { sort: { createdOn: -1, up: -1 }});
  } else {
    return Websites.find({},{ sort: { createdOn: -1, up: -1 }});
  } 
},
{{#each websites}}
  <div class="col-xs-12 col-md-3">
    <div class="thumbnail">
      <a href="{{url}}" class="site_name">{{title}}</a>
      <p class="site_desc">{{description}}</p>
      <br>
      <p class="upvote_button">Upvote: {{up}}</p>
      <p class="downvote_button">Downvote: {{down}}</p>
      <a href="#" class="btn btn-default js-upvote" id="upvote_button">
        <span class="glyphicon glyphicon-arrow-up" aria-hidden="true"></span>
      </a>
      <a href="#" class="btn btn-default js-downvote" id="downvote_button">
        <span class="glyphicon glyphicon-arrow-down" aria-hidden="true"></span>
      </a>
      <br>
      <p class="added-by">Added By: 
        <a href="#" class="js-filter">{{getUser createdBy}}</a>
      </p>
      <p>Added On: {{createdOn}}</p>
      <a href="/single_website/{{_id}}">Details</a>
    </div>
  </div>
{{/each}}

Answer №1

Sorting by multiple properties in Mongo means that the documents will be sorted first by the first property, then within those with the same value, it will use the second property for further ordering, and so on.

So, in your case, the websites will be sorted by the createdOn date initially, and then for those with the same date, they will be ordered by the up value. It seems like this may not be the desired outcome for you.

Additionally, since you are using a dictionary or mapping object for sorting, the order of the properties will depend on the JavaScript engine's implementation. Typically, it will follow the insertion order, such as 1) createdOn 2) up.

The [{a: 1, b: -1}] format will only work if your JavaScript implementation maintains the key order in objects. While most do this most of the time, it's important to ensure this in your case.

Perhaps you were looking for a sorting mechanism like this:

Websites.find({}, {
  sort: [
    ["up", "desc"], // Sort by "up" value first
    ["createdOn", "desc"] // then for websites with the same up value, order by date
  ]
})

Answer №2

Consider implementing a solution similar to the following:

Database.find({}).sort({dateCreated:-1, popularity:-1})

Hopefully, this approach proves successful.

If not, you may want to consider incorporating the following:

Database.ensureIndex({dateCreated: -1, popularity: -1})

Thank you

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

Difficulty with Nuxt + Vuex: Retrieving data from state using getter

Can anyone assist me with this issue? I am having trouble with my getters in Vuex not recognizing the state. Here is the code snippet: https://codesandbox.io/s/crazy-moon-35fiz?file=/store/user.js user.js: export const state = () => ({ user: { is ...

Tips for importing a different js file from an npm package without needing to include the entire node_modules path

When using the ES2016 import syntax to load the select2 library from an npm module via Webpack, everything works smoothly and the select2.js file is loaded from the node_modules directory. The node_modules directory also contains a full version of the lib ...

Error: The src for the image of the double cheeseburger could not be properly parsed by the `next/image` component

Could you kindly take a moment to review this? import Image from "next/image"; import { useState, useEffect } from "react"; import "@/data/data.json"; interface propsData { dish: { id: numbe ...

What's the easiest method for moving div content from side to side?

Working on a plugin for WordPress, I am faced with the task of moving content in a slider from left to right and right to left. My current attempt is as follows: var effect = 'slide'; // Set the options for the chosen effect type var opti ...

Using a timer to make Ajax calls twice on a single webpage

Can multiple ajax calls be made simultaneously on the same page to different receiving div tags? I am struggling to find a solution to this issue. I have a total of 3 pages: a home page, and two PHP pages named status and alert which echo the results. Wi ...

Tips for transferring data and events between named views within Vue Router

I have a layout structured like this: .------------------------+----------------. | Current Tab Title | Controls | +------------------------+----------------+ | Tab1 Tab2 [Tab3] | +---------------------------------------- ...

What could be the reason for the bottom edge of my central diagonal image having a darker border?

I can't figure out why the border on the bottom edge of my image is darker. You can check out the demo here. To get a closer look at the issue, you can open a software like GIMP and zoom in on the following image to see the difference in values: http ...

I am experiencing difficulties with displaying my array of JSX elements in the render function of my ReactJS application. What could be

I am currently working on a trivia application and encountering an issue with inserting an updated array of "Choice" elements for each question. Despite my efforts, whenever I attempt to insert an array of JSX elements, the array appears blank. This is qui ...

embed a hyperlink onto a live video at a designated moment within an HTML document

Can anyone help me figure out how to overlay a link over a video playing at a specific time on an HTML page? I know it's easy to do on Youtube, but I need to accomplish this task without using Youtube. :) Thank you in advance for any assistance! ...

Converting MongoDB Aggregation command into Java code

Here is the MongoDB shell command I am using: db.dais_employee.aggregate([ { "$redact": { "$cond": { "if": { "$gt": [ { "$subtract": [ "$modifiedon", "$createdon" ] }, ...

How can Swipe support help you slide a menu back in?

For implementing swipe support on my landing page carousel, I included jquery.mobile.custom.min.js. However, I am facing a challenge with adding swipe support to "close" the menu. Essentially, swiping left should have the same effect as clicking the butto ...

The NextJS App directory consistently stores the retrieved data in the cache, regardless of any no-cache options that may have been configured

Despite trying various online advice, I am still facing the issue of cached fetched data. I am using a mongodb server, and even though I add data to the server, I can only see the new data on the server itself, not on the website (before the NextJS project ...

Is your Bootstrap input displaying the has-error class with a glyphicon, but the alignment is not vertically centered?

What is the reason for the misalignment of glyphicon-warning-sign form-control-feedback vertically in the code below after applying font-size: 20px; to the label? <div class="container"> <div class="content align-left contact"> ...

Display a span element using jQuery datatable to indicate that the update operation was

I have implemented inline editing using jQuery Datatables. Currently, I am trying to display a green checkmark when a record gets updated. Below is the ajax call that populates the table: $.ajax({ url: 'api/massEditorSummary.php', type: &ap ...

Incorporate chat functionality into Angular using an embedded script

Recently, I encountered an issue with inserting an online chat using a Javascript script into my website. My initial plan was to add it directly to my app.component.html, but unfortunately, it didn't display as expected. I'm now exploring option ...

Issue with Bootstrap Carousel: all elements displayed at once

I'm in the process of building a carousel. I have set up the structure, but I only want five blocks to be visible initially, with the sixth block appearing after clicking an arrow. How can I achieve this? My strategy: (adopted from here) img{ b ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

Customize the text color of the active tab in Material-UI Tabs

I am facing a situation where I have this specific object: const tabStyle = { default_tab:{ color: '#68C222', width: '33.3%', backgroundColor: '#FFFFFF', fontSize: 15 }, active_tab: ...

How to send data to res.render in Node.js?

I'm new to working with node.js. In my index.ejs file, I have included a header.ejs file. Everything seems to be functioning properly except for the fact that I am unable to pass values to the variable status in the header.ejs. index.ejs <html& ...

Discover the nearest class and smoothly expand it with the slideDown function in jQuery

Hey there, I'm working on implementing a "View More" button on my page. The button will reveal another unordered list that currently has the class of "hidden-list". When the user clicks on "View More", I want it to slideToggle the hidden-list element ...