首页 > 解决方案 > FeathersJS 为集合创建复合索引

问题描述

FeathersJS 服务有没有办法为 MongoDB 数据库创建复合索引?

标签: mongodbfeathersjscompound-index

解决方案


找到你创建 MongoDB 客户端的地方。如果您使用 FeatherJS 生成器,-它可能位于src/mongodb.js. 在客户端已经可用的承诺结果中, - 获取集合并添加索引:

// 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);
}

推荐阅读