首页 > 解决方案 > 如何创建具有本地字段和引用字段 mongoose 的复合索引?

问题描述

我正在使用 Mongoose 和 MongoDB。

我想根据架构中的字段和引用架构中的字段进行查询。这是我正在查询的模型模式。

let schema = mongoose.Schema({
    parent_facility : { type: mongoose.Schema.Types.ObjectId, ref: 'Facility', required: true },
    thirdPartyId : mongoose.Schema.Types.Mixed
});

这是我想做的查询:

const modelsFound = await Model.find({thirdPartyId: 'randomidhere', parent_facility.status: 'complete'}).exec();

我该如何为此建立索引?

编辑:

这似乎按我想要的方式工作

schema.createIndex({thirdPartyId: 1, 'parent_facility.status': 1});

标签: mongodbmongoosemongoose-schema

解决方案


尝试这个:

Model.index({'thirdPartyId': 1, 'parent_facility': 1})

推荐阅读