Search code examples
javascriptnode.jsmongodbmongoose

Mongoose - aggregate is not a function


I am developing a function to abstract the Model used to query my MongoDB.

I have multiple models using the same schema, but I need to use only 1 function.

I am doing this:

const pricesSchema = {
    sold:...,
    createdAt:...
}


const Model1 = mongoose.model('Model1', pricesSchema);
const Model2 = mongoose.model('Model2', pricesSchema);

const getModelFromString = (model) => {
    switch(model) {
        case 'cars' || 'boats': {
            return Model1
        }
        case 'houses' || 'buildings': {
            return Model2
        }
    }
}

But when I consume these models in an abstract way, I am facing the following issue:

// ...
const Model = getModelFromString('cars')
Model.aggregate(...)


// TypeError: Model.aggregate is not a function ....

Solution

  • It’s not a proper check in switch case. If you want to check for multiple values in a single case, you can try the following:

    case 'cars':
    case 'boats':
        // your logic
    

    Or another approach:

    switch (true) {
        case (['cars', 'boats'].includes(model)):
            // your logic 
    }