Conditional condition building mongoose

Viewed 35

Each document has a number of dates, that I want to allow both sorting on, and filtering on. The date filtering should apply depending on the input sortBy.

This works

Starting off, I am successfully adding conditional .where's:

        // input examples

        var fromUnixms, toUnixms; // some unix ms timestamps
        var filters = ['createdAt', 'publishAt', 'publishFrom', 'publishTo'] // available date fields
        var sortBy = 'createdAt'; // the field we want to sort on

        // let's build a condition, 
        // looping through the sortable fields and filter based on what is sorted on

        let query = model.find();
        for (var i = 0; i < filters.length; i++) {
            if (sortBy == filters[i].fieldName) {
                query.where(filters[i].fieldName).gte(fromUnixms);
                query.where(filters[i].fieldName).lte(toUnixms);

                console.log("filtering on " + filters[i].fieldName 
                    + " between " + moment(fromUnixms) 
                    + " and " + moment(toUnixms);
                }
            }
        }

        query.sort(sortBy);

The goal

What doesn't work is now to add an .or(...)

The query should return docs that either

  • has a publishAt within the duration fromUnixms - toUnixms
  • has a duration publishFrom - publishTo overlapping the duration fromUnixms - toUnixms

What I've tried

                 if (sortBy == filters[i].fieldName) {
                    query.or([
                        {
                            filters[i].fieldName: {
                                $gte: fromUnixms,
                                $lte: toUnixms
                            }
                        },
                        {
                            // overlapping duration operands would go here
                        }
                    ]);

Typescript doesn't allow the key dynamic like this (filters[i].fieldName above) in the object, saying expecting a : where the dot is.

Extracting to a variable compiles, but doesn't hit: Mongoose probably interprets it as if I'm looking for a field called "aFieldName" instead of "createdAt", the value of sortBy.

                // ...
                var aFieldName = filters[i].fieldName;
                if (sortBy == filters[i].fieldName) {
                    query.or([
                        {
                            aFieldName: {

Mustaches obv doesn't compile either, but illustrates what I try to achieve here:

                    query.or([
                        {
                            {{ filters[i].fieldName }} : {
0 Answers
Related