我想在我的查询中添加一个where()子句,但是conditionally.具体来说,我只希望在URL中传递sepecific querystring参数时添加它.这可能吗?如果可能的话,我该怎么做?

router.get('/questions', function (req, res) {
    knex('questions')
        .select('question', 'correct', 'incorrect')
        .limit(50)
        .where('somecolumn', req.query.param) // <-- only if param exists
        .then(function (results) {
            res.send(results);
        });
});

推荐答案

您可以将查询存储在变量中,应用条件where子句,然后执行它,如下所示:

router.get('/questions', function(req, res) {
  var query = knex('questions')
              .select('question', 'correct', 'incorrect')
              .limit(50);

  if(req.query.param == some_condition)
    query.where('somecolumn', req.query.param) // <-- only if param exists
  else
    query.where('somecolumn', req.query.param2) // <-- for instance

  query.then(function(results) {
    //query success
    res.send(results);
  })
  .then(null, function(err) {
    //query fail
    res.status(500).send(err);
  });
});

Node.js相关问答推荐

使用NodeJS在S3上传文件时的格式问题

赫斯基添加命令已弃用?

如何解决无法获得本地颁发者证书的问题

聚合发布/订阅消息

如何在医学中按patientId查找一个并同时插入多个数据

如果我在 tsx 文件中使用了use client,ssr 会如何发生?

如何使用Stripe测试失败的收费?

结合后端(Express)和前端(Angular)路由

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

为什么我的 npm 脚本中的 glob 不起作用?

Winston http 日志(log)级别的行为与 info 不同

postman 发送请求……永远

如何在 mongoDB 中进行全动态搜索?

如何限制 cron 表单将消息推送到 RabbitMQ?

TypeError:请求路径包含未转义的字符,我该如何解决这个问题

Express.js:没有这样的文件或目录

npm 出现无法读取依赖项错误

Node.js:如何附加到正在运行的进程并使用控制台调试服务器?

路由后的 Node Express 4 中间件

从 JavaScript 文件或 REPL 中 require()'ing CoffeeScript 文件