Stuart Fong
Stuart Fong

Reputation: 633

Mongo sort not returning data in order

I am trying to fetch the documents from the db in an order from most likes to least and I keep running into an error. I created a few documents with likes of 1, 2 and 3 and the order that is returned is 2, 3, 1. It is really strange because when I first start up the server, it works fine, but I found that after around 20 mins of working on my project(not touching the code I am about to post), I realized that it wasn't returning the docs in proper order. Could this be a bug in Meteor? Or is it a problem on my side? Anyway here is the code where I am trying to fetch the docs in order.

renderNotesByLike.js

import React from "react";
import { Tracker } from "meteor/tracker";
import { Link, withRouter } from "react-router-dom"

import { Notes } from "./../../methods/methods";

 class RenderNotesByLike extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      notes: []
    };
  }
  renderNotes(notes){
    return notes.map((note) => {
      return(
        <div key={note._id} className="note-list" onClick={() => {this.props.history.push(`/fullSize/${note._id}`)}}>
          <div className="left inline">
            <p><strong>{note.title}</strong></p>
            <span className="removeOnSmallDevice">{note.userEmail}</span>
          </div>
          <div className="right inline">
            <span>Subject: <strong>{note.subject}, {note.unit}</strong></span>
            <br />
            <span className="removeOnSmallDevice">⬆ {note.likes.length} ⬇ {note.dislikes.length}</span>
          </div>
        </div>
      )
    })
  }
  componentDidMount() {
    this.tracker = Tracker.autorun(() => {
      Meteor.subscribe('notes');
      const notes = Notes.find({subject: this.props.subject}, {sort: {likes: -1}}).fetch();
      notes.map((note) => {console.log(note.likes.length)})
      this.setState({ notes })
    });
  }
  componentWillReceiveProps(nextProps) {
    this.tracker = Tracker.autorun(() => {
      Meteor.subscribe('notes');
      const notes = Notes.find({subject: nextProps.subject}, {sort: {likes: -1}}).fetch();
      this.setState({ notes });
    });
  }
  componentWillUnmount() {
    this.tracker.stop()
  }
  render(){
    return(
      <div className="center">
        {this.renderNotes(this.state.notes)}
      </div>
    )
  }
}
export default withRouter(RenderNotesByLike);

The publication for notes is pretty basic:

Meteor.publish('notes', function () {
  return Notes.find()
});

I do realize that a possible problem would be because I am publishing all the notes and I have to publish the ones I want to be filtered. But I did it the exact same way with the CreatedAt property and that works just fine.

Example Data

cloudinaryData:
{data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
createdAt:
1506224240000
description:""
dislikes:[]
imageURL:["AImageURL.jpg"]
likes:["d@d"]
subject:"Food"
title:"a"
unit:"a"
userEmail:"d@d"
userId:"rSGkexdzzPnckiGbd"
_id:"GPJa8qTZyDHPkpuYo"
__proto__:Object

Notes Schema:

"notes.insert"(noteInfo){
    noteInfo.imageURL.map((url) => {
      const URLSchema = new SimpleSchema({
        imageURL:{
            type:String,
            label:"Your image URL",
            regEx: SimpleSchema.RegEx.Url
        }
      }).validate({ imageURL:url })
    })

    Notes.insert({
      title: noteInfo.title,
      subject: noteInfo.subject,
      description: noteInfo.description,
      imageURL: noteInfo.imageURL,
      userId: noteInfo.userId,
      userEmail: noteInfo.userEmail,
      unit: noteInfo.unit,
      likes: [],
      dislikes: [],
      createdAt: noteInfo.createdAt,
      cloudinaryData: noteInfo.cloudinaryData
    })
    console.log("Note Inserted", noteInfo)
  } 

Upvotes: 0

Views: 129

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20227

You're sorting based on an array, not the length of the array. {sort: {likes: -1}} is not going to give you predictable results. Try explicitly sorting the fetched array of documents using underscore.js' _.sortBy() function.

componentDidMount() {
  this.tracker = Tracker.autorun(() => {
    Meteor.subscribe('notes');
    let notes = Notes.find({subject: this.props.subject}).fetch();
    notes = _.sortBy(notes,(n) => { return n.likes.length});
    this.setState({ notes })
  });
}

Upvotes: 2

Related Questions