如果提供了函数参数,则在MongoDB中应用过滤器



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

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

如果提供了title和authorName过滤器,我该如何只应用它们?同样,如果提供了sortBy参数,我将如何仅对查询进行排序?对此,是否有通用的最佳实践?

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

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

正如一个想法,根据参数修改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((,否则它将永远不会运行。

最新更新