【问题标题】:How do I index a field on a mongoose Schema that uses a discriminator?如何索引使用鉴别器的猫鼬模式上的字段?
【发布时间】:2021-07-16 23:38:56
【问题描述】:

在我开始使用鉴别器后开始出现错误。

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");

这会返回错误Refill.index is not a function

【问题讨论】:

    标签: node.js mongodb mongoose-schema


    【解决方案1】:

    在 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");
    

    【讨论】:

      【解决方案2】:

      我刚刚取出了Refill.index({ location: "2dsphere" });,我的其余代码工作正常,显然不需要索引该字段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 2018-08-21
        • 2017-09-24
        • 2016-12-12
        • 1970-01-01
        • 2021-02-16
        • 2016-02-07
        相关资源
        最近更新 更多