2
votes

I have 2 schema in mongoose as follows:

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

Is there some problem in PointSchema.js as it is giving following error:

TypeError: Invalid schema configuration: 2dsphere is not a valid type at path index.

Followed this documentation to create PointSchema.js: https://mongoosejs.com/docs/geojson.html

1

1 Answers

5
votes

I solved my problem with the next configuration in the model!

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