简体   繁体   English

如何正确构造此MongoDB排序查询?

[英]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. 我想在将数据传递给Mongo之前在后端构造一个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) 在代码中,req.query.so是排序类型(如name或id),req.query.sd是排序方向(1表示升序,-1表示降序)

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(). 我对Mongo不是很熟悉,我在网上发现的关于这个错误的大多数问题来自试图将数组而不是对象传递给.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. 我认为问题是通过使用替换语法$ {req.query.so}我创建了一个字符串,而不是一个对象,但我不确定这一点。 Please advise me on how to fix this. 请告诉我如何解决这个问题。

The replacement syntax is fine, you can see in the error message that you get name and 1 . 替换语法很好,您可以在错误消息中看到您获得name1 The issue is that you're creating sort as a string by using the back-ticks ` ` . 问题是,你正在创建sort使用反单引号作为字符串` `

`{${req.query.so}: ${req.query.sd}}` => "{name: 1}" `{${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 但是如果你把它创建为一个对象var sort = {}并添加params它应该工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM