使用$ near和$ maxDistance一起查询MongoDB不会返回任何结果

时间:2018-11-21 10:54:22

标签: javascript node.js mongodb mongoose

我的MongoDB中有一个这样定义的模型

var Structure = {
    idMission: String,
    type: { type: String, enum: ['arena', 'gym', 'injury', 'shop', 'street', 'structure'], required: true },
    name: { type: String, required: true },
    description: String,
    address: Schema.Types.Mixed,
    messaggi: Array,
    ratipoingsList: Array,
    rating: Number,
    owner: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    coord:
    // type : { type: String, index: true },
    { type: [Number], index: '2dsphere' },
    photos: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Image' }],
    coverPhoto: { type: mongoose.Schema.Types.ObjectId, ref: 'Image' },
    validated: { type: Boolean, default: false },
    missionId: String,
    __t: String,
    location: {
        region: String,
        nation: String,
        city: String
    }
};

var StructureSchema = new mongoose.Schema(base, {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
    test: 'kind',
    timestamps: true
}).plugin(mongoosePaginate);

如您所见,它遵循猫鼬标准。 当我尝试定义查询以将所有最接近的结构恢复到某个点时,尽管数据库确实有结果,但我不会得到任何结果。 这是我正在使用的查询

  var LAT = parseFloat(req.body.lat);
  var LNG = parseFloat(req.body.lng);
  var accuracy = 50000; //50km
  var point = { type: 'Point', coordinates: [LAT, LNG] };

  query = { $and: [{ $or: [{ validated: true }] }, { 'coord': {$near: {$geometry: point,$maxDistance: accuracy}}}] };
据我了解,

是基于2d球形物体的。使用此查询,我得到的响应没有对象,这不是我期望的行为,因为我有至少2个最接近查询结构的结构。

{
    "success": true,
    "count": 0,
    "structures": []
}

如果删除$ maxDistance参数,会发生以下情况:Mongoose DO查找值(实际上,我在数据库中拥有的所有值)

{
    "success": true,
    "count": 4,
    "structures": [
        {
            "_id": "5bf52ea5ad36430730df85a1",
            "name": "Test",
            "type": "structure",
            "coord": [
                41.899402,
                12.640591
            ],
            "validated": true,
            "id": "5bf52ea5ad36430730df85a1"
        },
        {
            "_id": "5bf526df2855722bf8d885ae",
            "name": "San",
            "type": "structure",
            "coord": [
                41.965234,
                12.546633
            ],
            "validated": true,
            "id": "5bf526df2855722bf8d885ae"
        },
        {
            "_id": "5bf3dbe095d01d2304a5c4b7",
            "name": "San lollo",
            "type": "structure",
            "coord": [
                41.966627,
                12.547382
            ],
            "validated": true,
            "id": "5bf3dbe095d01d2304a5c4b7"
        },
        {
            "_id": "5bf52d8fad36430730df85a0",
            "name": "Sanfrancesco",
            "type": "structure",
            "coord": [
                42.296604,
                12.182036
            ],
            "validated": true,
            "id": "5bf52d8fad36430730df85a0"
        }
    ]
}

此查询中我在哪里错了?

0 个答案:

没有答案