FeathersJS create compound index for collection

559 views Asked by At

Is there any way with FeathersJS service to create a compound index for a MongoDB DB?

1

There are 1 answers

0
justlo0king On

Find the place where you create MongoDB client. If you used FeatherJS generator, - it is probably at src/mongodb.js. In the promise result where client is already available, - get the collection and add indexes:

// src/app.ts
import mongodb from './mongodb';
...
app.configure(mongodb);
...



// src/mongodb.ts
export default function (app: Application): void {
  const connection = app.get(`mongodb`);
  const database = connection.substr(connection.lastIndexOf(`/`) + 1);
  const mongoClient:Promise<Db> = MongoClient.connect(connection, {
    useNewUrlParser: true, useUnifiedTopology: true
  }).then((client:MongoClient) => {
    const db:Db = client.db(database);
    try {
      db.collection(`users`).createIndex({ name: 1 });
    } catch(error:any) {
      console.error(`mongodb: failed to created indexes, error: `, error);
    }
    return db;
  });

  app.set(`mongoClient`, mongoClient);
}