我在猫鼬中有 2 个模式,如下所示:
点架构.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
};
Run Code Online (Sandbox Code Playgroud)
设备架构.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);
Run Code Online (Sandbox Code Playgroud)
PointSchema.js 中是否存在一些问题,因为它给出了以下错误:
TypeError: Invalid schema configuration:
2dsphereis not a valid type at pathindex。
按照此文档创建 PointSchema.js:https ://mongoosejs.com/docs/geojson.html
小智 5
我用模型中的下一个配置解决了我的问题!
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);
};
Run Code Online (Sandbox Code Playgroud)