【问题标题】:Using an arbitrary number of query params to filter results in mongoose使用任意数量的查询参数来过滤猫鼬中的结果
【发布时间】:2015-12-03 11:13:26
【问题描述】:

我正在使用 node express 和 mongodb 以及 mongoose 构建一个 API。 我有一个处理用户帖子的帖子资源,并且希望能够对帖子资源执行各种查询。 例如,我有一个函数返回所有帖子,如下所示:

// Gets a list of Posts
exports.index = function(req, res) {
  console.log(req.query);
  Post.findAsync()
    .then(mUtil.responseWithResult(res))
    .catch(mUtil.handleError(res));
};

我正在寻找一种处理请求可能附带的任何其他查询参数的好方法。

/posts 将返回所有帖子,但/posts?user=12 将返回 id 为 12 的用户的帖子,/posts?likes=12 将返回 12 个或更多赞的帖子。

我如何检查并应用这些查询参数来过滤和返回结果,因为它们可能存在也可能不存在。 谢谢;)

【问题讨论】:

  • 你在这里问什么?如果您使用/posts?user=12&likes=12,那么如何将其转换为您的查询?您当然可以只输入req.params,但当然如果“喜欢”的意思是“大于”指定的数字,那么您将需要操作该对象。 MongoDB 查询只是对象结构,因此任何对象操作代码都适用。

标签: node.js mongodb mongoose


【解决方案1】:

如果user=12 表示“id 为 12 的用户”,likes=12 是如何表示“喜欢大于 12”的?您的查询需要更具描述性。您可以通过传递对象数组来做到这一点。以可以这样解释的方式发送您的查询:

var filters = [
{
    param: "likes",
    type: "greater"
    value: 12
},
{
    param: "user",
    type: "equal",
    value: "12"
}]

var query = Post.find();

filters.forEach(function(filter) {

    if (filter.type === "equal") {
        query.where(filter.param).equals(filter.value);
    }
    else if (filter.type === "greater") {
        query.where(filter.param).gt(filter.value);
    }
    // etc,,,
})

query.exec(callback);

【讨论】:

    猜你喜欢
    • 2019-02-18
    • 2015-11-28
    • 2021-11-21
    • 1970-01-01
    • 2020-10-08
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多