MongoDB => findOne 或 find 查询下一个对象? (流星/反应)

问题描述 投票:0回答:2

想要找到与当前对象相关的下一个和上一个对象。

这就是我所拥有的

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}};

我知道这是不正确的,当然它会返回对象,但它不会是最近的对象,而且我也有可能返回当前对象。

我想要做的是返回下一个或上一个对象,其中我的选择器是投票,我还想确保使用 Id 排除当前对象,那么也很有可能多个对象将具有相同的投票数。

现在已经连续 12 个小时在这上面了,我几乎回到了我开始的地方,所以非常感谢一些例子来让我理解这个问题,不再不确定我是否应该使用 find 或 findOne。

这是完整代码

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>;
  }
});
javascript mongodb meteor reactjs
2个回答
2
投票

您需要:

  • 排除当前id
  • 按适当的方向排序
  • 仅选择一个结果

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 }});

0
投票

我在Next.js中就是这样的

 const user = await (await User).findOne({ _id: { $ne: "ID HERE" } }); 

const user = await User.findOne({ _id: { $ne: "ID HERE" } }); 
© www.soinside.com 2019 - 2024. All rights reserved.