MongoDB查询-将函数传递给Model.find()

时间:2019-06-20 12:51:15

标签: mongodb mongoose mongodb-query

通过将function作为参数传递给Model.find()->这样的Model.find(searchCondition),我在查询MongoDB(猫鼬)时遇到问题。我希望你能帮助我。

// Fetching patients from the database
exports.getPatients = (req, res, next) => {
    const criterionSearchCategory = req.query.kriterijumPretrage;
    const ageSearchCategory = req.query.kriterijumGodina;
    const searchInputValue = req.query.pojamPretrage;

    console.log({ [criterionSearchCategory]: { [ageSearchCategory]: Number([searchInputValue]) }});

    // Patient search condition, based on selected option from select dropdown
    function searchCondition() {
        if (criterionSearchCategory == 'undefined') {
            return {};
        } else if (criterionSearchCategory == 'age') {
            return { [criterionSearchCategory]: { [ageSearchCategory] : Number([searchInputValue]) }}
        } else {
            return { [criterionSearchCategory]: { $in: [ "/^" + searchInputValue + "/i" ]}}
        }
    }

   ...
    const patientQuery = Patient.find(searchCondition);
getPatients(patientsPerPage: number, currentPage: number, criterionSearchCategory: string, searchInputValue: string, ageSearchCategory: any) {
        const queryParams = `?pacijenataPoStranici=${patientsPerPage}&trenutnaStranica=${currentPage}&kriterijumPretrage=${criterionSearchCategory}&pojamPretrage=${searchInputValue}&kriterijumGodina=${ageSearchCategory}`;
        this.http
            .get<{ message: string, patients: any, maxPatients: number }>( BACKEND_URL + queryParams)
            // Execute map on every data that makes it through Observable stream
            .pipe(map((patientData) => {

我想在手动传递查询参数时进行修饰,例如const patientQuery = Patient.find({ age: { '$gt': 30 } });将正确地提取适当的患者,但是当我传递函数时,例如const patientQuery = Patient.find(searchCondition);然后不起作用。

第一个问题,是否可以像这样将函数作为参数传递?

任何建议将不胜感激。谢谢

0 个答案:

没有答案