我有一个 Mongoose 模式和模型定义如下:
var mongoose = require('mongoose')
, Schema = new mongoose.Schema({
email: {
index: {
sparse: true,
unique: true
},
lowercase: true,
required: true,
trim: true,
type: String
},
location: {
index: '2dsphere',
type: [Number]
}
})
, User = module.exports = mongoose.model('User', Schema);
如果我尝试:
var user = new User({ email: 'user@example.com' });
user.save(function(err) {
if (err) return done(err);
should.not.exist(err);
done();
});
我收到错误消息:
MongoError: Can't extract geo keys from object, malformed geometry?:{}
尽管此架构中的位置字段不是必需的,但它似乎无论如何都是如此。我已经尝试添加 default: [0,0]
来规避这个错误,但是它看起来有点像黑客,因为这显然不是一个好的默认值,理想情况下架构不需要用户始终拥有一个位置。
MongoDB/mongoose 的地理空间索引是否意味着被索引的字段是必需的?
最佳答案
对于 mongoose 3.8.12,您设置默认值:
var UserSchema = new Schema({
location: {
type: {
type: String,
enum: ['Point'],
default: 'Point',
},
coordinates: {
type: [Number],
default: [0, 0],
}
}
});
UserSchema.index({location: '2dsphere'});
关于node.js - 在 Mongoose 模式上应用 2dsphere 索引是否会强制要求位置字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388836/