Mongo排序不按顺序返回数据

时间:2017-09-24 17:51:09

标签: meteor

我试图从大多数喜欢到最少的顺序从db中获取文档,并且我一直遇到错误。我创建了一些类似于1,2和3的文档,返回的顺序是2,3,1。这真的很奇怪,因为当我第一次启动服务器时,它工作正常,但我发现在20左右之后在我的项目上工作的时间(不接触我即将发布的代码),我意识到它没有以正确的顺序返回文档。这可能是Meteor中的一个错误吗?或者这是我身边的问题?无论如何这里是我试图按顺序获取文档的代码。

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

notes的出版物非常基本:

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

我确实意识到一个可能的问题是因为我正在发布所有笔记,我必须发布我想要过滤的那些笔记。但我用CreatedAt属性完全相同的方式做了它,并且工作得很好。

示例数据

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架构:

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

1 个答案:

答案 0 :(得分:2)

您要根据数组进行排序,而不是根据数组的长度进行排序。 {sort: {likes: -1}}不会给你可预测的结果。尝试使用underscore.js'_.sortBy()函数显式排序获取的文档数组。

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