MongoDB使用聚合$ lookup或在Node.js中填充两个集合

时间:2016-08-29 08:03:49

标签: node.js mongodb mongodb-query aggregation-framework mongodb-aggregation

这是两个系列'架构

var activitySchema = new Schema({

    activity_id: {type: String, index: {unique: true}, required: true}, 

    begin_date : String,
    ...
})

var registrationSchema = new Schema({

    activity_id: {type: String, index: {unique: true}, required: true}, 

    registration_id: {type:String, trim: true, index: true ,required: true },

    email       : String,
    ...
})

我想在同一个查询中activity.begin_date , registration.id , registration.email。我能怎么做?我在互联网上找到了一些解决方案,但仍然不知道是否使用填充或聚合$lookup(这个似乎是新的)。

这是我试过的方式,但根本没有工作。

models.Registration.aggregate([

        {
            $lookup: {
                from: "Activity",
                localField: "activity_id",
                foreignField: "activity_id",
                as: "activity_docs"
            }
        },
        {"$unwind" : "activity_docs"},

    ], function( err , result ){
        if(result){
            fullDoc = result;
        }else{
            next( err );
        }
    })

1 个答案:

答案 0 :(得分:1)

activity_id应为ObjectId数据类型。 ObjectId documentation

如果要使用pupoluate,则必须将ref用于其他架构。 Population documentation

var activitySchema = new Schema({

    begin_date : String,
    ...
})
var Activity= mongoose.model('Activity', activitySchema );


var registrationSchema = new Schema({

    activity_id: {type: Schema.Types.ObjectId, ref : 'Activity', required: true}, 
    email       : String,
    ...
})



  var Registration = mongoose.model('Registration', registrationSchema);

所以查询如:

var query = Registration.find({_id: 'registration_id parameter'});
query.select('_id activity_id email');
query.populate('activity_id','_id begin_date');
query.exec(function(error,result){
   if(error){
        /// handle error
   }else{
       // handle result
   }
});