这是两个系列'架构
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 );
}
})
答案 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
}
});