【问题标题】:Apply filter in MongoDB if function argument provided如果提供了函数参数,则在 MongoDB 中应用过滤器
【发布时间】:2021-09-23 05:51:31
【问题描述】:

我正在使用 TypeScript、Node.js、Mongoose 和 MongoDB。如果我有类似的功能:

async function getAllBooks(title?: string, authorName?: string, sortBy?) {
    const books = await bookModel.find().sort();

    return books;
}

如果提供了标题和作者姓名过滤器,我将如何着手?同样,如果提供了 sortBy 参数,我将如何仅对查询进行排序?对此有通用的最佳做法吗?

例如,如果我提供标题和 sortBy 字段,我希望查询看起来像这样:

async function getAllBooks(title?: string, authorName?: string, sortBy?) {
    const books = await bookModel.find(title: title).sort(sortBy.field: sortBy.sortDirection);

    return books;
}

【问题讨论】:

  • 提供undefined基本上和不提供字段一样。

标签: node.js typescript mongodb express mongoose


【解决方案1】:

只是一个思路,根据参数修改find​​对象:

async function getAllBooks(title?: string, authorName?: string, sortBy?) {
  let findThis = {};
  if(title) findThis.title=title;
  if(authorName) findThis.authorName=authorName;
 
  const books = await bookModel.find(findThis).sort(sortBy.field: sortBy.sortDirection).exec();

  return books;
}

添加 exec() 否则它永远不会运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 2016-06-04
    • 2020-02-29
    • 1970-01-01
    • 2016-03-18
    相关资源
    最近更新 更多