@cme-pro/mongoose-search
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

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/
        }
      ]
    }
*/

Package Sidebar

Install

npm i @cme-pro/mongoose-search

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

20.3 kB

Total Files

19

Last publish

Collaborators

  • svengau
  • martinratinaud