如何在使用区分符的猫鼬模式上索引字段?

时间:2019-04-11 11:25:20

标签: node.js mongodb mongoose-schema

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

$MYSQL_DUPLICATE_CODES=array(1062,23000);
try {
   $prep->execute($values);
   // do other things if successfully inserted
} catch (PDOException $e) {
   if (in_array($e->getCode(),$MYSQL_DUPLICATE_CODES)) {
      // duplicate entry, do something else
   } else {
      // an error other than duplicate entry occurred
   }
}

这将返回错误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");

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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