Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 views
in Technique[技术] by (71.8m points)

javascript - How to sort data with dynamic fields in PouchDB?

I'm having this query to index first_name and sort data according to it and it's working fine

try {
  Users.createIndex({
    index: { fields: ['first_name'] }
  }).then(function (response) {
    console.log(response);
  }).catch(function (err) {
    console.log(err);
  });
  const users = (await Users.find({
    limit, skip: limit * (page - 1),
    selector: {first_name: {$gt: null}},
    sort: [ { 'first_name' : 'asc'} ]
  })).docs;

But when I try to use variables it triggers an error

Error: Cannot sort on field(s) "orderBy" when using the default index

Code

orderBy = (query.params !== undefined && query.params.orderBy !== undefined) ? query.params.orderBy.sortField : 'first_name',
sortOrder = (query.params !== undefined && query.params.orderBy !== undefined) ? query.params.orderBy.sortOrder : 'asc'

console.log('orderBy: ' + orderBy) // first_name
console.log('sortOrder: ' + sortOrder) // asc

try {
  Users.createIndex({
    index: { fields: [orderBy] }
  }).then(function (response) {
    console.log(response);
  }).catch(function (err) {
    console.log(err);
  });
  const users = (await Users.find({
    limit, skip: limit * (page - 1),
    selector: {orderBy: {$gt: null}},
    sort: [ { orderBy : sortOrder } ]
  })).docs;

How can I edit this to make it work with dynamic variable just like the static variable?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The variable orderBy is not going to be substituted by value in the following code

 selector: {orderBy: {$gt: null}},
 sort: [ { orderBy : sortOrder } ]

The code evaluates orderBy literally. To assign a dynamic key to an object, use the object indexer:

myObject[myVar] = myVal;

Therfore in your code, something like this should do.

const query = {
    selector: {},
    sort: []
  };
  // setup selector
  query.selector[prop] = {
    $gt: null
  };
  // setup sort
  let sortParam = {};
  sortParam[prop] = sortDirection;
  query.sort.push(sortParam);

I added a pouchDB snippet illustrating that concept.

let db;

// init example db instance
async function initDb() {

  db = new PouchDB('test', {
    adapter: 'memory'
  });

  await db.bulkDocs(getDocsToInstall());
}



initDb().then(async() => {
  await db.createIndex({
    index: {
      fields: ['first_name']
    }
  });
  await doQuery("first_name", "desc");
});

async function doQuery(prop, sortDirection) {
  const query = {
    selector: {},
    sort: []
  };
  // setup selector
  query.selector[prop] = {
    $gt: null
  };
  // setup sort
  let sortParam = {};
  sortParam[prop] = sortDirection;
  query.sort.push(sortParam);
  // log the query
  console.log(JSON.stringify(query, undefined, 3));
  // exec the query
  const users = (await db.find(query)).docs;
  users.forEach(d => console.log(d[prop]));
  
}
// canned test documents
function getDocsToInstall() {
  return [{
      first_name: "Jerry"
    },
    {
      first_name: "Bobby"
    },
    {
      first_name: "Phil"
    },
    {
      first_name: "Donna"
    },
    {
      first_name: "Ron"
    },
    {
      first_name: "Mickey"
    },
    {
      first_name: "Bill"
    },
    {
      first_name: "Tom"
    },
    {
      first_name: "Keith"
    },
    {
      first_name: "Brent"
    },
    {
      first_name: "Vince"
    },

  ]
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/pouchdb.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.find.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...