Skip to content

Mongoose schema plugin to search on multiple fields. Support search on ObjectID, Regex or Mongodb text indexes

License

Notifications You must be signed in to change notification settings

cme-pro/mongoose-search

Repository files navigation

npm node tests downloads

mongoose-search

Mongoose schema plugin to search on multiple fields. Supports:

  • Search on ObjectID
  • Regex search, or custom search
  • MongoDB text indexes search (MongoDB >= 2.4, mongoose >=3.6).

There are already multiple plugins to manage search, but most of them are handling too much (like filtering or pagination). This plugin only build the query related to a fulltext search, and let other plugins handle their part (pagination, ...).

Installation

$ npm install @cme-pro/mongoose-search --save

or

$ yarn add @cme-pro/mongoose-search

Overview

Adding plugin to the schema

const mongoose = require("mongoose");
const mongooseSearch = require("@cme-pro/mongoose-search");
const { Schema } = mongoose;

const BlogPost = new Schema({
  title: { type: String, searchable: true },
  body: { type: String, searchable: (q: string) => new RegExp(`${q}`) },
  excerpt: { type: String }
});

BlogPost.index({ title: "text", body: "text" });

const BlogPostModel = mongoose.model("Post", BlogPost);

Usage

Simple search:

const query = BlogPostModel.searchQuery("reactjs");

/**
  query = {
      $or: [
        {
          $text: { $search: "reactjs" }
        },
        {
          title: /^reactjs/
        },
        {
          description: /reactjs/
        }
      ]
    }
*/

Search on ObjectID:

const query = BlogPostModel.searchQuery("5cfa2debabe4d93a5b35897c");

/**
  query = { $_id_: "5cfa2debabe4d93a5b35897c" }
*/

Custom search

const query = BlogPostModel.searchQuery("reactjs", { fields: { title: true } });

/**
  query = {
      $or: [
        {
          $text: { $search: "reactjs" }
        },
        {
          title: /^reactjs/
        }
      ]
    }
*/

About

Mongoose schema plugin to search on multiple fields. Support search on ObjectID, Regex or Mongodb text indexes

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •