Git Product home page Git Product logo

mongoose-atlas-search's Introduction

mongoose-atlas-search

Plugin to use MongoDB Atlas Search feature.

Flexible mongoose plugin that converts simple find function to aggregation with Atlas Search support, if search value is in query.

Atlas Search Docs

Requirements

Atlas Search is available on all cluster tiers running MongoDB version 4.2 or later. Non-Atlas MongoDB deployments can not use it!

Important! Indexes must be created manually!

Installation

npm install mongoose-atlas-search --save

Usage

const mongoose = require('mongoose');
const atlasPlugin = require('mongoose-atlas-search');


const Schema = mongoose.Schema;

const UserSchema = new Schema(
  {
    name: String,
    email: String,
    languagel: String,
  },
  {collection: 'users'}
);


const UserModel = mongoose.model('User', UserSchema);


//atlasPlugin.initialize(<options>);
atlasPlugin.initialize({
  model: UserModel,
  overwriteFind: true,
  searchKey: 'search',
  addFields: {
    id: '$_id'
  },
  searchFunction: query => {
    return {
      'wildcard': {
        'query': `${query}*`,
        'path': '_id',
        'allowAnalyzedField': true
      }
    }
  }

});


(async () => {
  const resultWithSearch = await UserModel.find({search: 'test user'}); //aggregation is used
  const resultWithoutSearch = await UserModel.find({name: 'test user'}); //standard "find" is used
})();

Options

option type description required
model object Instance of mongoose.Model true
searchKey string Key name in query to detect that Atlas Search should be used. Default: 'search' false
overwriteFind boolean If true, standard "find" function is overwritten. If false - plugin adds new function Model.search(query, projection, opts). Default: true false
searchFunction function Need to customize search step in aggregation. See example above. By default, text operator is used: {text: {searchValue, path} false
path string or [string] Required if searchFunction option is not defined depends on searchFunction option
addFields object Add aggregation step "addFields". In example above "id" field is added. false

Meta

Sergey Reus - [email protected] - GitHub - stackoverflow

Feel free to create issues or PRs.

mongoose-atlas-search's People

Contributors

rocknrolla777 avatar

Stargazers

Bilal İŞLER avatar Osama Shegem avatar  avatar  avatar

mongoose-atlas-search's Issues

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'search' of undefined

when i try to use this plugin, it just gives this error when i do a .find( ) query, with the error in the title. i was just trying to use it with the basic provided example, adding just a .connect( ) to connect to a DB. WHY?

`const mongoose = require('mongoose');
const atlasPlugin = require('mongoose-atlas-search');

const Schema = mongoose.Schema;

const UserSchema = new Schema(
{
name: String,
email: String,
languagel: String,
},
{collection: 'movies'}
);
UserSchema.set('validateBeforeSave', false);

const UserModel = mongoose.model('User', UserSchema);

//atlasPlugin.initialize();
atlasPlugin.initialize({
model: UserModel,
overwriteFind: false,
addFields: {
id: '$_id'
},
searchFunction: query => {
return {
'wildcard': {
'query': ${query}*,
'path': '_id',
'allowAnalyzedField': true
}
}
}

});
mongoose.connect("<DB_Connection>").then(async()=>{
console.log(await UserModel.find().exec());
});`
changing the searchKey value, or removing it. making overwriteFind true or false, didnt help.

Counts, limits and skips

I have added the plugin to my model:

const PersonModel = mongoose.model<IPersonDB>('Person', PersonSchema);

atlasPlugin.initialize({
  model: PersonModel,
  overwriteFind: true,
  searchKey: 'search',
  addFields: {
    id: '$_id'
  },
  searchFunction: query => {
    return {
      'wildcard': {
        'query': `${query}*`,
        'path': '_id',
        'allowAnalyzedField': true
      }
    };
  }
});

I am now trying to adjust a query that I previously had:

    const searchTerm = 'mysearch term';
    const query: Record<string, any> = {
       deleted: { $ne: true },
    };

    query.$text = {
      $search: filter.query,
      $caseSensitive: false,
      $diacriticSensitive: false,
      $language: 'french'
    };
    return {
      entries: await Person.find(query).limit(limit).skip(offset).lean(),
      total: await Person.find(query).countDocuments()
    };

to:

    const searchTerm = 'mysearch term';
    const query: Record<string, any> = {
       deleted: { $ne: true },
    };

    query.search = searchTerm;

    return {
      entries: await Person.find(query).limit(limit).skip(offset).lean(),
      total: await Person.find(query).countDocuments()
    };```

While dropping the `lean()` call seems to resolve the first part, I am not sure how to get the total document count when using the plugin?

Error: default query param is required!

Error: default query param is required!

Documentation is REQUIRED
Configured Plugins As per Doc :
//atlasPlugin.initialize();
atlasPlugin.initialize({
model: ProfileModel,
overwriteFind: false,
searchKey: 'default',
addFields: {
id: '$_id',
fullname: '$_fullname',
email: '$_email',
countryData: '$_countryData',
mobile: '$_mobile'
},
searchFunction: query => {
return {
'wildcard': {
'query': ${query}*,
'allowAnalyzedField': true
}
}
}
});

Creating Query Like Below :
ProfileModel.search({
query: search
}, function(errSearch, search) {
});

Please provide more documentation for the same

getting this error :
Error: default query param is required!
at Function.model.search (/server/platforms/mybusiness platform/node_modules/mongoose-atlas-search/dist/index.js:22:27)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.