node.js如何在Inner Mongodb中查找文档

时间:2017-11-18 05:12:52

标签: javascript node.js

请教我如何在Inner Mongodb中找到一份文件。我想在市场上为您带来一些坐标。我该怎么办?

/**
 * 데이터베이스 스키마를 정의하는 모듈
 *
 * @date 2016-11-10
 * @author Mike
 */

//var crypto = require('crypto');

var Schema = {};

Schema.createSchema = function(mongoose) {

    // 스키마 정의
    var ItemSchema = mongoose.Schema({
        itemName : {type: String, index: 'hashed', 'default':''}
        ,market : {
             marketName: {type: String, index: 'hashed', 'default':''}
           , marketId: {type: String, required: true, 'default':''} //마켓 고유번호
           , geometry: {
                type: {type:String, default:'Point'},
                coordinates: [{type:'Number'}]
                }
            , tel: {type: String, required: true, 'default':''}
            , address: { data: Buffer, contentType: String,default:''  }
        }

        ,price : { type: 'Number',default:''}
        ,disPrice: {type: 'Number',default:''}
        ,count: {type: 'Number',default:''}

        ,expireTime : {type: Date, index: {unique: false} }

    });

    console.log('ItemSchema 정의함.');


     ItemSchema.index({geometry:'2dsphere'});


    ItemSchema.static('findNear',function(longitude,latitude,maxDistance,callback){
       console.log('findNear 호출됨')

        this.find().where('geometry').near({

            center:{

                type:'Point',
                coordinates:[parseFloat(longitude),parseFloat(latitude)]

        },

            maxDistance:maxDistance
        }).exec(callback);

    });      



    return ItemSchema;
};

// module.exports에 UserSchema 객체 직접 할당
module.exports = Schema;

这是路由器

var findNearItem = function(req,res){     console.log(' findNearData。');

var paramLongitude = req.body.longitude || req.query.longitude;
var paramLatitude = req.body.latitude || req.query.latitude;
var maxDistance = 10000;

var database = req.app.get('database');

database.ItemModel.findNear(paramLongitude, paramLatitude, maxDistance, function(err, results) {
    if(err) {
        console.dir(err);
        return;
    }

    console.log('결과 -> ' + JSON.stringify(results));

    var context = {
        results:results
    };

    var output = JSON.stringify(context);
    res.writeHead(200,{'Content-Type':'application/json;charset=utf-8'});
    res.write(output);
    res.end();
});

};

这是配置

{文件:' ./项',路径:' /过程/ findNearItem',方法:' findNearItem',类型:'交&# 39;}

2 个答案:

答案 0 :(得分:0)

查找查询返回整个记录文档,即使查询条件检查记录的子文档中的属性如坐标,但在您的情况下,您只想返回坐标子文档。

我建议使用聚合。

this.aggregate(
    [{
        $group: {
            _id:"$market.geometry.coordinates"
          }
    }])

如果要在maxDistance字段中具有坐标的最大值

db.getCollection('market').aggregate(
    [{
        $group: {
            _id:"$market.geometry.coordinates"
          }},{
          $project: { maxDistance: { $max: "$_id" }} //_id here is refering to "market.geometry.coordinates"
      }])

架构静态方法中的管道构建器技术:

ItemSchema.static('findNear',function(longitude,latitude,maxDistance,callback){
   console.log('findNear 호출됨');

return this.aggregate().group({
            _id:"$market.geometry.coordinates"
          }).project({
            maxDistance: { $max: "$_id" }
          }).exec(callback);

});

答案 1 :(得分:0)

抱歉,我无法使用聚合,我通过修改ItemSchema解决了这个问题。

var ItemSchema = mongoose.Schema({
    itemName : {type: String, index: 'hashed', 'default':''}
       , marketName: {type: String, index: 'hashed', 'default':''}
       , marketId: {type: String, required: true, 'default':''} //마켓 고유번호
       , geometry: {
            type: {type:String, default:'Point'},
            coordinates: [{type:'Number'}]
            }
        , tel: {type: String, required: true, 'default':''}
        , address: { data: Buffer, contentType: String,default:''  }        
        ,price : { type: 'Number',default:''}
        ,disPrice: {type: 'Number',default:''}
        ,count: {type: 'Number',default:''}
        ,expireTime : {type: Date, index: {unique: false} }

});