MongoDB使用aggregation $lookup或在Node.js中填充来连接两个集合



下面是两个集合的模式

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

activity_id应为ObjectId数据类型。ObjectId文档

如果要使用pupoluate,则必须对其他模式使用ref。人口文档

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

相关内容

  • 没有找到相关文章

最新更新