如何为使用鉴别器的 mongoose Schema 上的字段编制索引?
How do I index a field on a mongoose Schema that uses a discriminator?
错误是在我开始使用鉴别器后出现的。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const Refill = Base.discriminator(
"Refill",
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
})
);
Refill.index({ location: "2dsphere" });
module.exports = mongoose.model("Refill");
这个returns错误Refill.index is not a function
我刚刚删除了 Refill.index({ location: "2dsphere" });
,我的其余代码工作正常,显然不需要索引该字段。
在 Mongoose 中,必须在模式而非模型上创建索引。在您的例子中, Refill
对象是一个模型。一种方法是分三步实施:
- 创建架构
- 将索引添加到架构
- 创建模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const refillSchema =
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
});
refillSchema.index({ location: "2dsphere" });
const Refill = Base.discriminator("Refill", refillSchema);
module.exports = mongoose.model("Refill");
错误是在我开始使用鉴别器后出现的。
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const Refill = Base.discriminator(
"Refill",
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
})
);
Refill.index({ location: "2dsphere" });
module.exports = mongoose.model("Refill");
这个returns错误Refill.index is not a function
我刚刚删除了 Refill.index({ location: "2dsphere" });
,我的其余代码工作正常,显然不需要索引该字段。
在 Mongoose 中,必须在模式而非模型上创建索引。在您的例子中, Refill
对象是一个模型。一种方法是分三步实施:
- 创建架构
- 将索引添加到架构
- 创建模型
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const refillSchema =
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
});
refillSchema.index({ location: "2dsphere" });
const Refill = Base.discriminator("Refill", refillSchema);
module.exports = mongoose.model("Refill");