2dsphere在路径`index`处不是有效类型

时间:2019-12-10 16:09:20

标签: node.js mongoose

我的猫鼬有2个架构,如下所示:

PointSchema.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PointSchema = new mongoose.Schema({
  type: {
    type: String,
    enum: ['Point']
  },
  coordinates: {
    type: [Number]
  },
  index: {
    type: '2dsphere',
    sparse: true
  }
});

module.exports = {
  PointSchema
};

DeviceSchema.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PointSchema = require('./PointSchema').PointSchema;

const DeviceSchema = mongoose.Schema({
  name: String,
  location: {
    type: PointSchema,
    default: null
  }
}, {
  collection: 'devices',
  timestamps: {
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  }
});

module.exports = mongoose.model('Device', DeviceSchema);

PointSchema.js 是否存在某些问题,因为它会出现以下错误:

  

TypeError:无效的架构配置:2dsphere无效   在路径index中输入。

遵循此文档创建PointSchema.js:https://mongoosejs.com/docs/geojson.html

1 个答案:

答案 0 :(得分:2)

我用模型中的下一个配置解决了我的问题!

module.exports = (mongoose) => {
      const DomainSchema = new mongoose.Schema({
        domain_id: { type: Number },
        name: String,
        domain_data: {
          type: { type: String },
          coordinates: { type: Array },
        },
      });
      DomainSchema.index({ domain_data: '2dsphere' });
      return mongoose.model('Domain', DomainSchema);
    };