使用节点js在MongoDB中“加入”两个集合

时间:2015-07-17 16:06:08

标签: node.js mongodb express mongodb-query

我正在尝试使用节点js在mongodb中的两个集合之间进行查询。

我在db中有这两个集合:

旅行

{               
    "_id":ObjectId("55a922531e35772c1b17d4a0"),
    "name":"trip_name",
    "waypoints":[
        "4c828999d8086dcb03877752",
        "4dd2ae657d8b4c6585f1a6fd",
        "4c59c3e4f346c928a8634dca"
    ],
    "line_points":[
        [
            42.850937,
            13.569256
        ],
        [
            42.85109,
            13.569377
        ],
        [
            42.851131,
            13.569225
        ]
    ],
    "time":"00:10:23",
    "distance":6.622,
    "hashKey":"object:8207"
};

Poi

{  
      "_id":"4c828999d8086dcb03877752",
      "type":"Feature",
      "geometry":{  
         "type":"Point",
         "coordinates":[  
            13.575249910354614,
            42.85484995890166
         ]
      },
      "properties":{  
         "title":"Lorenz Cafè",
         "id":"4c828999d8086dcb03877752",
         "poi-type":1,
         "category":"ristorazione",
         "subCategory":"Café",
         "categoryIds":"4bf58dd8d48988d16d941735",
         "marker-color":"#FF7519",
         "marker-size":"small",
         "marker-symbol":"restaurant",
         "indirizzo":"Piazza del Popolo, 5",
         "citta":"Ascoli Piceno",
         "regione":"Marche"
      }

通过这条路线,我根据id那个步骤进行查询,我希望查询我会像这样恢复一个json:

我想要的结果

{"_id":"55a922531e35772c1b17d4a0","name":"trip_name","waypoints":[{"4c828999d8086dcb03877752":{"title":"Lorenz Cafè","id":"4c828999d8086dcb03877752","category":"ristorazione","position":{"lat":42.85484995890166,"lng":13.575249910354614}}},{"4dd2ae657d8b4c6585f1a6fd":{"title":"Ottica Di Ferdinando","id":"4dd2ae657d8b4c6585f1a6fd","category":"negozi","position":{"lat":42.85485741498569,"lng":13.57675423240643}}},{"4c59c3e4f346c928a8634dca":{"title":"Leopoldus Ristorante","id":"4c59c3e4f346c928a8634dca","category":"ristorazione","position":{"lat":42.85648980743132,"lng":13.575512766838072}}}],"line_points":[[42.850937,13.569256],[42.85109,13.569377],[42.851131,13.569225]],"time":"00:10:23","distance":6.622}

我实施了路线

/*
TRIP BY ID
 */
var j=0;
router.get('/:id', function(req, res) {
    db = req.db;
    var idString=req.params.id;
    var objId = new ObjectID(idString);
    var collection2=db.get('poilist');
    var collection = db.get('trip');

    collection.find({"_id": objId},{},function(e,docs){
        var trip=docs[0];
        var poi=[];
        var wp=trip.waypoints;

        for(var i=0; i< wp.length; i++)
        {
            collection2.find({"properties.id": wp[i]},function(e,docs2){
                poi[j]={
                        "title" : docs2[0].properties.title,
                        "id": docs2[0].properties.id,
                        "category": docs2[0].properties.category,
                        "position": {"lat":docs2[0].geometry.coordinates[1], "lng":docs2[0].geometry.coordinates[0]}
                    };
                    var id = wp[j];
                    wp[j]= {};
                    wp[j][id]=poi[j];
                    if(j==wp.length-1){
                        console.log('emit '+j);
                        emitter.emit('attesa' + j);
                    }else{
                        j++;
                    }

            });
        }
        emitter.once('attesa'+ (trip.waypoints.length-1) ,function() {
            j=0;
            console.log('once');

            res.json(trip);
        });
    });
});

此路线有效但如果您同时拨打多个电话,则不再有效。

我有一个想法:计算请求的数量,然后仔细检查这个地方的id是否在这次旅行中但看起来非常昂贵。 我想知道一个更实用的方法,用于在mongo中使用多个集合进行查询。 提前致谢

2 个答案:

答案 0 :(得分:6)

首先我建议你使用猫鼬。在此之前,您必须准备模型,例如:

var mongoose = require('mongoose')
  , Schema = mongoose.Schema

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
  _creator : { type: Number, ref: 'Person' },
  title    : String,
  fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

在此之后,当您想要“加入”时,您最常使用下一个方法:

Story.find().populate("fans");

对于moar http://mongoosejs.com/docs/populate.html

答案 1 :(得分:1)

在第一次请求时获取基本的JSON数据

  

{“_ id”:ObjectId(“55a922531e35772c1b17d4a0”),                   “名”:“TRIP_NAME”                   “航点”:                       “4c828999d8086dcb03877752”                       “4dd2ae657d8b4c6585f1a6fd”                       “4c59c3e4f346c928a8634dca”               ]   }

然后调用其他API,使用异步调用和promise来获取航点数据,一旦解决了promise,就合并它们。