Search code examples
javascriptmongodbmeteorreactjs

MongoDB => findOne or find querying next object? ( Meteor / React )


Want to find the next and previous object in relation to current.

This is what i have

this.props._id = currentId;

// Fetch current object data
data.video = Videos.findOne({_id: this.props._id});

// Using votes string from object above to find me objects 
data.next = Videos.findOne({votes: {$gte: data.video.votes}});
data.previous = Videos.findOne({votes: {$lte: data.video.votes}};

I know this is not correct, sure it will return objects but it will not be the nearest object and there is also a chance i will return current object.

What i want to do is to return next or previous object where my selector is votes, I also want to make sure to use Id to exclude current object, then there is also a good chance that several objects will have the same number of votes.

Have been on this for 12 hours straight now and am pretty much back where i started so would really appreciate some examples to make me wrap my head around this, Not sure anymore if i should use find or findOne.

Here is the complete code

VideoPage = React.createClass({
  mixins: [ReactMeteorData],
  getMeteorData() {
    var selector = {};
    var handle = Meteor.subscribe('videos', selector);
    var data = {};
    data.userId = Meteor.userId();
    data.video = Videos.findOne({_id: this.props._id});
    data.next = Videos.findOne({votes: {$gte: data.video.votes}});
    data.previous = Videos.findOne({votes: {$lte: data.video.votes}};
    console.log(data.video.votes);
    console.log(data.video);
    console.log(data.next);
    console.log(data.previous);


    return data;
  },


  getContent() {
    return <div>
    {this.data.video.votes}
      <Youtube video={this.data.video} />
    <LikeBox next={this.data.next._id} previous={this.data.previous._id} userId={this.data.userId} video={this.data.video} />
    </div>
    ;
  },


  render() {
    return <div>

      {(this.data.video)? this.getContent() :
        <Loading/>
      }

    </div>;
  }
});

Solution

  • You need to:

    • exclude the current id
    • sort in the appropriate direction
    • pick just one result

    js:

    data.video = Videos.findOne({ _id: currentId });
    
    // object with next highest vote total
    data.next = Videos.findOne({ _id: { $ne: currentId },
      votes: { $gte: data.video.votes }},{ sort: { votes: 1 }});
    
    // object with next lowest vote total
    data.previous = Videos.findOne({ _id: { $ne: currentId },
      votes: { $lte: data.video.votes },{ sort: { votes: -1 }});