简体   繁体   中英

node.js how to find a document inside Inner Mongodb

Please teach me how to find a document inside Inner Mongodb. I'd like to bring you some coordinates inside the market. What should I do?

/**
 * 데이터베이스 스키마를 정의하는 모듈
 *
 * @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;

this is router

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();
});

};

this is config

{file:'./item',path:'/process/findNearItem',method:'findNearItem',type:'post'}

The find query return the whole record document, even if the query condition checking on an attribute in the sub document of the record like coordinates but in your case you want to return just the coordinates sub document.

I suggest using aggregate.

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

If you want to have the max value of coordinates in a maxDistance field

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

Pipeline builder technique within schema static method:

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);

});

sorry I can't use aggregate, I solved the problem by modifying the 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} }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM