如何为$ near查询创建Mongoose Schema

时间:2016-05-18 10:30:31

标签: mongodb mongoose mongodb-query

我在MongoDB上创建了一个带有地理索引" 2dsphere"我的合作中有一个具有这种结构的元素:

{ 
    "_id" : ObjectId("573b2416130380fbf20c2610"), 
    "location" : { 
        "type" : "Point",
        "coordinates" : [ -73.856077, 40.848447 ] 
    }, 
    "marca" : "smart", 
    "stato" : "libera" 
}

如何在mongoose中为此结构创建架构?

1 个答案:

答案 0 :(得分:1)

假设集合名为Location,您可以将模式定义为:

var locationSchema = new mongoose.Schema({
    marca: { type: String, required: true }, 
    stato: { type: String, required: true }, 
    loc: {
        type: {
            type: "String",
            required: true,
            enum: ['Point', 'LineString', 'Polygon'],
            default: 'Point'
        },
        coordinates: [Number]
    }
});

locationSchema.index({'loc': '2dsphere'});
var Location = mongoose.model('Location', locationSchema);

或使用index

var locationSchema = new mongoose.Schema({
    marca: { type: String, required: true }, 
    stato: { type: String, required: true }, 
    loc: {
        type: {
            type: "String",
            required: true,
            enum: ['Point', 'LineString', 'Polygon'],
            default: 'Point'
        },
        coordinates: [Number],
        index: { type: '2dsphere', sparse: true }
    }
});
var Location = mongoose.model('Location', locationSchema);