Search code examples
javascriptmongodbbson

How can I construct this MongoDB sort query properly?


I'm trying to construct a mongo sort query in the backed end before passing the data to Mongo. In the code, req.query.so is the sort type (like name or id) and req.query.sd is the sort direction (1 for ascending and -1 for descending)

This is the code that is raising an error:

exports.indexWithStatus = function (req, res) {
  // sort
  let sort = null
  if (req.query.so && req.query.sd) {
    sort = `{${req.query.so}: ${req.query.sd}}` // not being constructed 
correctly
  }

The error that I'm getting is:

name: 'MongoError',
message:
'Failed to parse: sort: "{name: 1}". \'sort\' field must be of BSON type object.',
ok: 0,
errmsg:
'Failed to parse: sort: "{name: 1}". \'sort\' field must be of BSON type 
object.',
 code: 9,
 codeName: 'FailedToParse' }

I'm not very familiar with Mongo, and most of the questions I found online about this error are from people who tried to pass an array not an object to .sort().

I think the problem is that by using the replacement syntax ${req.query.so} I am creating a string, and not an object, but I am not certain of this. Please advise me on how to fix this.


Solution

  • The replacement syntax is fine, you can see in the error message that you get name and 1. The issue is that you're creating sort as a string by using the back-ticks ` `.

    `{${req.query.so}: ${req.query.sd}}` => "{name: 1}"

    But if you create it as an object var sort = {} and add the params it should work

    sort[`${one}`] = `${two}` => {name: "1"}