【问题标题】:Cannot sort on field(s) xxx when using the default index使用默认索引时无法对字段 xxx 进行排序
【发布时间】:2022-02-02 20:11:26
【问题描述】:

我有以下 pouchdb 查询,我看这里没有任何问题,但它会抛出错误 Cannot sort on field(s) "createTime" when using the default index。关于如何解决这个问题的任何想法?每次查询都必须createIndex吗??

let getData = () => {
  let re = new RegExp('2017-09-06')
  db.createIndex({
    index: {
      fields: ['createTime'],
    }
  }).then((result)=>{
    return db.find({
      selector: {createTime: {$regex:re}},
      fields: ['createTime'],
      sort: ['createTime']
    }).then(function (result) {
      // handle result
      debugger
    }).catch(function (err) {
      console.log(err)
      debugger
    });
  })

}

【问题讨论】:

  • 有消息了吗?现在面临同样的问题!

标签: pouchdb


【解决方案1】:

我真的不知道为什么,但是添加带有 'gt: null' 的选择器似乎适用于我的情况。我正在使用 pouchDB v 6.4.1。你可以试试这些吗:

db.createIndex({
  index: {
    fields: ['createTime'],
  }
}).then((result) => {
  return db.find({
    selector: {
      $and: [
        { createTime: {'$gt': null} },
        { createTime: {'$regex': new RegExp('2017-09-06')}} }
      ]
    },
    fields: ['createTime'],
    sort: ['createTime']
  }
);

【讨论】:

    【解决方案2】:

    因此,在花了一些时间尝试解决此问题后,这是一个对我有用的简单解决方案:(结果我没有正确阅读文档,您必须包含字段以在选择器中排序为好吧)

    let sort_field = 'name'; 
    let selectorQuery = {
       latest: {$regex: ''},
       oldest: {$regex: ''},
       name: {$regex: ''},
    }
    
    
    clientsDB.createIndex({
       index: {
          fields: ['latest', 'oldest', 'name'] //specify all fields
       }
    }).then(() => {
        clientsDB.find({
           selector: selectorQuery,
           sort: [sort_field]
       }).then(res => {
           console.log(res.docs)
       }); 
    })
    

    它会相应地对它们进行排序。

    【讨论】:

      【解决方案3】:

      我已经为这个错误苦苦挣扎了很长时间。一个可能且隐藏得很好的原因是您的索引中可能有多个字段,但对于排序,顺序确实很重要。

      阅读插件代码:

      // e.g. ['a'], ['a', 'b'] is true, but ['b'], ['a', 'b'] is false
      function oneArrayIsSubArrayOfOther(left, right) {
      
      // check that at least one field in the user's query is represented
      // in the index. order matters in the case of sorts
      function checkIndexFieldsMatch(indexFields, sortOrder, fields) {
      

      我在任何地方都没有看到记录。

      工作代码:

      await db.createIndex({
        index: { fields: ['createdAt', 'kind'] }, // createdAt must be first
      });
      
      await db.find({
        selector: { kind: 'foo' },
        sort: ['createdAt']
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-24
        • 1970-01-01
        • 2018-07-09
        相关资源
        最近更新 更多