从MongooseJS获取“错误:无法使用带有数组的$ geoWithin”

时间:2013-09-01 03:03:38

标签: node.js mongodb mongoose

当我使用MongooseJS执行以下类型的查询时:

Place
  .find({location:{$geoWithin:{$box:[[0, -40],[151.0983703,-33.8674744]]}}})
  .exec(function(err, places) {
    ...
  });

我得到零结果,并在err

中返回以下消息
  

[错误:无法在数组中使用$ geoWithin。]

然而,如果我在命令行上直接对MongoDB执行完全相同的标准:

> db.places.find({location:{$geoWithin:{$box:[[0, -40],[151.0983703,-33.8674744]]}}})

我得到输出中显示的正确记录列表。

MongooseJS代码我做错了什么?

1 个答案:

答案 0 :(得分:0)

在我正在使用的Mongoose版本中,似乎没有实现$geoWithin

我暂时的解决方案是使用本机mongodb库,直到更新Mongoose的稳定版本并支持$geoWithin

var mongodb = require('mongodb');
mongodb.MongoClient.connect(app.get('mongodb connection string'), function(err, db) {
    if (err) throw err;

    db.collection('places')
        .find({location:{
            $geoWithin:{
                $box:[[Number(req.query.northEastLng), Number(req.query.northEastLat)], 
                      [Number(req.query.southWestLng), Number(req.query.southWestLat)]]}}})
        .toArray(function(err, results) {
            if (!results)
                results = [];

            res.render('nearbyplaces', {
                results: results
            });

            db.close();
        });
});

这很好用。

(注意:如果你真的想使用Mongoose,你可以从他们的Github页面下载最新的不稳定版本。我只是不愿意,因为它会使我的应用程序的部署复杂化。我希望能够下载只有npm install)的所有内容。