javascript - 尝试在 find() 中使用 $near 查询时出错

标签 javascript node.js mongodb mongoose

我正在尝试将 $near 运算符与 $find() 一起使用,但是我无法完成它。我尝试了两种方法

用户架构

var userSchema = new db.Schema({
  email: { type: String, unique: true, lowercase: true },
  password: { type: String, select: false },
  company_name: String,
  location_verified: { type:Boolean, default:false},
  account_verified: { type:Boolean, default:false},
  date_joined: {type:Date, default:Date.now},
  business_details: {
    business_phone: String,
    business_email: String,
    business_location:[]
  }
})

//index as 2d 
userSchema.index({ 'business_detail.business_location': '2d' });
var User = db.model('User', userSchema);

方法一

    var limit = req.query.limit || 10;
    var maxDistance = req.query.distance || 8;
    maxDistance /= 6371;
    var coords = [];
    coords[0] = 101.6833;
    coords[1] = 3.1333;
    User.find({
      'business_details.business_location': {
        $near: coords,
        $maxDistance: maxDistance
      }
    }).limit(limit).exec(function(err, locations) {
      if (err) {
        console.log("The ERROR:"+err);
      }
      console.log("The RESULT:"+locations);
    });

方法2

    var limit = req.query.limit || 10;
    var maxDistance = req.query.distance || 8;
    maxDistance /= 6371;
    var coords = [];
    coords[0] = 101.6833;
    coords[1] = 3.1333;

User.find({
  'business_details': {
    $near:{
      $geometry:{'business_location':coords},
      $maxDistance: maxDistance
    }
  }
}).limit(limit).exec(function(err, locations) {
  if (err) {
    console.log("The ERROR:"+err);
  }
  console.log("The RESULT:"+locations);
});

我已经检查了我的数据库索引,我尝试使用 $near 的字段有 2d 索引

> db.system.indexes.find();
{ "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "clairvy.users" }
{ "v" : 1, "unique" : true, "key" : { "email" : 1 }, "name" : "email_1", "ns" : "clairvy.users", "background" : true, "safe" : null }
{ "v" : 1, "key" : { "business_detail.business_location" : "2d" }, "name" : "business_detail.business_location_2d", "ns" : "clairvy.users", "background" : true, "safe" : null }

这就是我的文档的样子

"_id" : ObjectId("557ae162d3fb543275135f04"),
    "company_name" : "john inc",
    "email" : "example@gmail.com",
    "password" : "$2a$10$SDAXG8TrqjJIbvyGjpyQQuJDMTTDjMlNdpNQ9brsf4otGKr/CqI5i",
    "business_details" : {
        "business_phone" : "011112",
        "business_email" : "example@gmail.com",
        "business_fb" : "https://www.youtube.com/watch?v=NA4otP-v6iI",
        "business_about_us" : " asd sad sad sadasd",
        "business_tags" : [
            {
                "name" : "Marina Augustine",
                "email" : "m.augustine@exampleas.com",
                "image" : "http://lorempixel.com/50/50/people?0",
                "_lowername" : "marina augustine"
            },
            {
                "name" : "Oddr Sarno",
                "email" : "o.sarno@exampleas.com",
                "image" : "http://lorempixel.com/50/50/people?1",
                "_lowername" : "oddr sarno"
            }
        ],
        "business_location" : [
            101.6867332275391,
            3.1285006558498596
        ],
        "business_price_range" : 2,
        "business_preparation_time_range" : 2
    }

两种方法都给我返回相同的结果,即错误“MongoError:n/a”我可以知道我在哪一部分犯了错误吗? 感谢您的帮助,谢谢

最佳答案

您的索引位于错误的命名空间中。你拥有什么:

{ "business_detail.business_location" : "2d" }, 

它应该是什么:

{ "business_details.business_location" : "2d" }, 

所以这里正确的字段是“business_details”,更正为:

db.users.ensureIndex({ "business_details.business_location": "2d })

或者以其他方式在 Mongoose 模式中定义该索引。但也要删除集合上任何其他错误命名的索引,因为某些“geo”命令会被多个索引混淆。

db.users.dropIndex({ "business_detail.business_location": "2d" })

由于 MongoDB 是“无模式”的,因此添加文档中不存在的索引不会产生错误。由于“无模式”,MongoDB 本身无法知道“有一天”或“某个文档”中可能存在数据。

添加到架构定义中是一个很好的做法,这样代码中的某些点就可以反射(reflect)您的意图:

userSchema.index({ "business_details.business_location": "2d" });

关于javascript - 尝试在 find() 中使用 $near 查询时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30815878/

相关文章:

node.js - nodejs createReadStream 空文件

javascript - 需要原型(prototype)内部或外部的功能?

mongodb - 如何将 nitrous.io 框中的 mongodb 二进制文件更新为 2.4.x 版本?

node.js - 按子文档拆分文档

Javascript 正则表达式挂起(使用 v8)

javascript - 未捕获的类型错误 : Cannot read property 'submit' of null for stripe payment

javascript - 需要帮助了解创建 Vue 实例的区别,这是最佳实践,以及何时使用每个选项?

node.js - 如何在 Apple Silicon M1 上原生安装 NodeJS?

javascript - 尝试在 Angular 客户端显示数据

javascript - 如何从 Javascript 中的集合数组中提取键的值