How to search multiple fields in Mongoose model

January 03, 2020

Let us suppose that you’ve a customer model in mongoose and want to search multiple fields in it. Kind of like a search term that you can use to check it across multiple fields like name, mobile, email, etc.

Here’s how to do it:

const mongoose = require('mongoose');
 
const { Schema } = mongoose;
 
const customerSchema = new Schema(
    {
        name: {
            type: String,
            trim: true
        },
        address: {
            type: String,
            trim: true
        },
        email: {
            type: String,
            trim: true
        },
        mobileNumber: {
            type: Number,
            trim: true
        },
        age: {
            type: Number,
            trim: true
        },
        dob: {
            type: Date
        },
        occupation: {
            type: String,
            trim: true
        }
    },
    { timestamps: true }
);
 
 
customerSchema.statics.search = function(searchTerm) {
    const stringSearchFields = ['name', 'email'];
    const numberSearchFields = ['mobileNumber'];
    const query = {
        $or: [
            ...stringSearchFields.map(field => ({
                [field]: new RegExp('^' + searchTerm, 'i')
            })),
            ...numberSearchFields.map(field => ({
                $where: `/^${searchTerm}.*/.test(this.${field})`
            }))
        ]
    };
    return this.find(query);
};
 
module.exports = mongoose.model('Customer', customerSchema);

👋 I'm Ashik Nesin • Frontend Engineer @Chargebee 👨‍💻• I write about modern Javascript & building web apps

© 2021 Nesin Technologies LLP