【问题标题】:Using geoNear in Mongoose在猫鼬中使用 geoNear
【发布时间】:2018-07-22 01:43:27
【问题描述】:

我一直在尝试用猫鼬确定忍者与 geoLocation 点的距离。我已经尝试了所有方法,但不知何故我找不到 Mongoose 的正确文档,这些是一些新的变化。

像这样:

const express = require('express');
const router = express.Router();
const Ninja = require('../models/ninja');

// get a list of ninjas from the database
router.get('/ninjas', (req, res, next) => {
    Ninja.aggregate([
        {
            $geoNear: {
                near: { type: "Point", coordinates: [ parseFloat(req.query.lng) , parseFloat(req.query.lat) ] },
                maxDistance: 100000,
                distanceField: "distance",
                spherical: true
            }
        }
    ]).then(function(ninjas){
        res.send(ninjas);
    }).catch(next)
});

不过,当我通过 Postman 将参数添加到 URL 时,我找不到它。

这是我的架构:

const mongoose = require ('mongoose');
const Schema = mongoose.Schema;

// CREATE GEOLOCATION SCHEMA
const GeoSchema = new Schema({
   type:{
       type: String,
       default: "Point"
   },
   coordinates: {
       type: [Number],
       index: "2dsphere"
   }
});

// CREATE NINJA SCHEMA AND MODEL
const NinjaSchema = new Schema({
    "name": {
        type: String,
        required: [true, 'Name field is required']
    },
    "rank": {
        type: String,
    },
    "available": {
        type: Boolean,
        default: false
    },
    "geometry": GeoSchema
});

const Ninja = mongoose.model('ninja', NinjaSchema);

module.exports = Ninja;

【问题讨论】:

  • 您找到答案了吗?如果没有,我可以知道您在服务器日志中遇到的错误吗?
  • 您确定查询参数的顺序正确吗?例如,您的 get 请求应该类似于 /ninjas?lng=-80&lat=25,具体取决于您是否有位置为经度 -80.*** 和纬度 25.*** 的 ninja

标签: node.js database mongodb mongoose aggregate


【解决方案1】:

更正您的忍者模型和架构代码

// create ninja Schema & model
const NinjaSchema = new Schema({
name: {
    type: String,
    required: [true, 'Name field is required']
},
rank: {
    type: String
},
available: {
    type: Boolean,
    default: false
},
geometry: GeoSchema

});

【讨论】:

    猜你喜欢
    • 2020-04-27
    • 2019-01-30
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-11
    • 2017-01-08
    相关资源
    最近更新 更多