Giter VIP home page Giter VIP logo

mongoolia's Introduction

mongoolia

Keep your Mongoose schemas synced with Algolia

While this plugin was created by Algolia, it is not an officially supported API client. It is possible that future major versions of Mongoose break compatibility, or require changes.

This plugin will automatically synchronise your models with an Algolia index every time a new document is added, updated or removed.

You can also index your whole collection if you didn't use this plugin when you started using mongoose.

How to

Only supports mongoose v4

First install the library:

  • > yarn add mongoolia OR
  • > npm add mongoolia -S

Then you need to specify which fields of your schema you want to index with Algolia and register the plugin to your mongoose model created with this schema:

// ES6
import mongoose from 'mongoose';
import mongoolia from 'mongoolia';

// ES5
const mongoose = require('mongoose');
const mongoolia = require('mongoolia').default;

// Pass `{algoliaIndex: true}` to push theses attributes for indexing to Algolia
const BookSchema = new mongoose.Schema({
  title: { type: String, required: true, algoliaIndex: true },
  author: { type: String, required: true, algoliaIndex: true },
  description: { type: String, required: true, algoliaIndex: true }
});

// Specify your Algolia credentials which you can find into your dashboard
BookSchema.plugin(mongoolia, {
  appId: 'xxxxx',
  apiKey: 'xxxx',
  indexName: 'xxxx'
})

Options

Option name Type Description
appId* string The Algolia application ID
apiKey* string The Algolia admin API key
indexName* string The name of the index you want to push data

Methods

After applying the mongoolia plugin to your mongoose model it registers new static methods:

Model.syncWithAlgolia(): Promise

Index the whole collection into your Algolia index.

Model.clearAlgoliaIndex(): Promise

Clears your Algolia index and remove _algoliaObjectID from your documents.

Model.setAlgoliaIndexSettings(settings: {}, forwardToReplicas: boolean): Promise

Set one or more settings of the Algolia index, the full settings list is available here.

Model.algoliaSearch({ query: string, params?: {}, populate?: boolean }): Promise

Search into your Algolia index for a specific query. You can customize the search parameters as well.

You can find the full list of search parameters here, you should look for settings tagged with search.

The server response will look like:

{
  "hits": [
    {
      "firstname": "Jimmie",
      "lastname": "Barninger",
      "objectID": "433",
      "_highlightResult": {
        "firstname": {
          "value": "<em>Jimmie</em>",
          "matchLevel": "partial"
        },
        "lastname": {
          "value": "Barninger",
          "matchLevel": "none"
        },
        "company": {
          "value": "California <em>Paint</em> & Wlpaper Str",
          "matchLevel": "partial"
        }
      }
    }
  ],
  "page": 0,
  "nbHits": 1,
  "nbPages": 1,
  "hitsPerPage": 20,
  "processingTimeMS": 1,
  "query": "jimmie paint",
  "params": "query=jimmie+paint&attributesToRetrieve=firstname,lastname&hitsPerPage=50"
}

mongoolia's People

Contributors

0xflotus avatar iam4x avatar sarahdayan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongoolia's Issues

_algoliaObjectID is not being returned

I noticed that "_algoliaObjectID" is not being returned when I query my model. I need to know its ID to update it on Algolia when I update my local db. How can I achieve that?

p.s. When I update my db using methods like findOneAndUpdate() or findByIdAndUpdate() it simply doesn't update any data on Algolia

TypeError: doc.pushToAlgolia is not a function (mongoolia 1.0.3, mongoose 5.10)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var algoliasearch = require('algoliasearch');
const mongoolia = require('mongoolia').default;

const VAR_ENV = require('../config.js');


const BookSchema = new Schema({
    title: {
        type: String,
        algoliaIndex: true,
        required: true,
        trim: true
    },
});

BookSchema.plugin(mongoolia, {
    appId: VAR_ENV.ALGOLIA_APP_ID,
    apiKey: VAR_ENV.ALGOLIA_API_KEY,
    indexName: VAR_ENV.ALGOLIA_PREFIX + '_BOOK',
    debug: true
})

const Book = mongoose.model('Book', BookSchema)

Book.syncWithAlgolia();

module.exports = Book;

Indexing Referenced Schemas

I have a mongoose schema that references a 'User' schema. I'd like certain fields to be indexed into Algolia like the users name, and a few other fields, but the problem is that all of the attributes within user are being sent over to Algolia, including things like the hashed password (which I don't want indexed). Is it currently possible to tell Mongolia to not index certain fields within referenced documents?

const EventSchema = new mongoose.Schema({
  name: { type: String, required: true, algoliaIndex: true },
  start_at: { type: Date, required: true, algoliaIndex: true },
  end_at: { type: Date, required: true, algoliaIndex: true },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    index: true,
    algoliaIndex: true
  }
});

doc.pushToAlgolia is not a function

It throws this error when I run

User.syncWithAlgolia().then((r) => console.log(r)).catch((err) => console.log(err));

(node:3160) DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
POST /graphql 200 891.404 ms - 12130
TypeError: doc.pushToAlgolia is not a function
    at /Users/damiisdandy/Development/jetronmall/api/node_modules/mongoolia/dist/algolia-mongoose-model.js:44:22
    at Array.map (<anonymous>)
    at /Users/damiisdandy/Development/jetronmall/api/node_modules/mongoolia/dist/algolia-mongoose-model.js:43:32
    at Generator.next (<anonymous>)
    at step (/Users/damiisdandy/Development/jetronmall/api/node_modules/mongoolia/dist/algolia-mongoose-model.js:13:191)
    at /Users/damiisdandy/Development/jetronmall/api/node_modules/mongoolia/dist/algolia-mongoose-model.js:13:361
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

This is my model file

import { Schema, model } from 'mongoose';
import bcrypt from 'bcryptjs';
// @ts-ignore
import mongoolia from 'mongoolia';
import { algoliaConfig, PASSWORD_SALT_ROUNDS } from '../../config';

const User = new Schema(
  {
    firstName: { type: String, algoliaIndex: true },
    lastName: { type: String, algoliaIndex: true },
    phone: String,
    email: { type: String, algoliaIndex: true },
    password: String,
    isConfirmed: {
      type: Boolean,
      default: false,
    },
    roles: [{ type: Schema.Types.ObjectId, ref: 'Role' }],
  },
  { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }
);

User.pre('save', async function (next) {
  try {
    if (!this.isModified('password')) return next();
    // @ts-ignore
    this.password = await bcrypt.hash(this.password, PASSWORD_SALT_ROUNDS);
    next();
  } catch (err: any) {
    next(err);
  }
});

User.plugin(mongoolia, {
  ...algoliaConfig,
  indexName: 'users'
});

User.methods.validatePassword = async function (data) {
  // @ts-ignore
  return bcrypt.compare(data, this.password);
};

export default model('User', User);

but User.algoliaSearch works fine

TypeError: doc.pushToAlgolia is not a function

I'm trying to use Mongoolia with my project and I've encountered an error that I can't explain.

// the userSchema is defined here, excluded for brevity
userSchema.plugin(mongoolia, {
    appId: "<redacted>",
    apiKey: "<redacted>",
    indexName: "<redacted>"
});

const User = mongoose.model("User", userSchema);

User.syncWithAlgolia()
    .catch(err => { console.log(err); });

As far as I know, this seems right. I've also set the algoliaIndex: true values where appropriate and imported Mongoolia with:

const mongoolia = require("mongoolia").default;

However, I get this error:

TypeError: doc.pushToAlgolia is not a function
    at C:\Users\Administrator.GRAPH-PC\Documents\PROJECTS\CDR-App\node_modules\mongoolia\dist\algolia-mongoose-model.js:44:22
    at Array.map (<anonymous>)
    at C:\Users\Administrator.GRAPH-PC\Documents\PROJECTS\CDR-App\node_modules\mongoolia\dist\algolia-mongoose-model.js:43:32
    at Generator.next (<anonymous>)
    at step (C:\Users\Administrator.GRAPH-PC\Documents\PROJECTS\CDR-App\node_modules\mongoolia\dist\algolia-mongoose-model.js:13:191)
    at C:\Users\Administrator.GRAPH-PC\Documents\PROJECTS\CDR-App\node_modules\mongoolia\dist\algolia-mongoose-model.js:13:361
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

Any ideas?
Thank you, and please feel free to ask for any more code that you may need to reproduce my issue.

TypeError: TagSchema.syncWithAlgolia is not a function

Hey everyone,

I want to use mongoolia to sync my MongoDB with Algolia but am currently facing this bug when running the code:

TypeError: TagSchema.syncWithAlgolia is not a function

This is my code so far:

//meme schema
var meme = require('../app/model/meme');
var mongoose = require('mongoose');
const mongoolia = require('mongoolia').default;
var algoliasearch = require('algoliasearch');

const TagSchema = mongoose.Schema({
  tagarray: { type: String, required: true, algoliaIndex: true },
});

TagSchema.plugin(mongoolia, {
  appId: 'Qfdgdfgdf',
  apiKey: 'd93fdgdfgffg',
  indexName: 'test1'

})

TagSchema.syncWithAlgolia();

What am I doing wrong?

I was referred here by the algolia support team so hopefully, I get my problem solved here.

Thanks.

TypeError: doc.pushToAlgolia is not a function

I get this error. here is my model.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var algoliasearch = require('algoliasearch');
const mongoolia = require('mongoolia').default;

//create jobs schema and model
const CompanySchema = new Schema({
name: {
type: String,
required: [true, 'Company Name field is required.']
},
about: {
type: String,
required: [true, 'Description field is required.']
},
profilePic: {
type: String,
required: [true, 'Image link is required.']
},
registeredDate: {
type: Date,
default: Date.now
},
jobsPosted: {
type: Array,
required: [true, 'Array of Job ids is required.']
},
telephone: {
type: String,
required: [true, 'Telephone field is required.']
},
email: {
type: String,
required: [true, 'Email Address is required.']
},
website: {
type: String,
required: [false]
},
});

// Specify your Algolia credentials which you can find into your dashboard
CompanySchema.plugin(mongoolia, {
appId: 'xx',
apiKey: 'xxx',
indexName: 'company'
});

const Company = mongoose.model('company',CompanySchema);

Company.syncWithAlgolia().then(function(data){
console.log(data);
}).catch(function(err){
console.log(err);
});

module.exports = Company;

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.