【问题标题】:FeathersJS create compound index for collectionFeathersJS 为集合创建复合索引
【发布时间】:2019-04-16 06:43:03
【问题描述】:

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

【问题讨论】:

  • 您使用的是feathers-mongodb 还是feathers-mongoose?他们会有不同的方法来接近它。 AFAIK 简单的 feathers-mongodb 只允许您从注册服务返回 Collection 对象。因此,您只需这样做,然后像使用常规节点驱动程序一样调用createIndex()
  • 我正在使用feathers-mongodb。这个“createIndex()”应该在哪里完成?
  • 所以它基本上应该类似于service('service-name').Model.createIndex({ ... }),并为您的复合索引提供所有常规createIndex() 选项。适配器是nothing special,而Model 属性只是一个Collection 对象,如前所述。
  • 您好 Neil,很抱歉再次打扰您,但在我的上一个问题中,我的意思是应该在 FeathersJS 文件结构的哪个位置完成此操作?我在“servicename.service.js”文件中尝试过,在服务设置了服务变量的模型字段之后,但它似乎对我不起作用。您是否确切知道应该在 FeathersJS 文件结构中的哪个位置完成?谢谢!
  • 再次您好...我没有正确定义复合索引,现在它正在工作,但我仍然想知道我称为“createIndex()”的地方是否符合“FeathersJS” " 或者应该在不破坏 FeathersJS 预期流程的任何其他地方进行......

标签: mongodb feathersjs compound-index


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多