2

Here are two collections' schema

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,
    ...
})

I want activity.begin_date , registration.id , registration.email in the same query. How can I do? I've found some solutions on the internet, but still don't know whether using populate or aggregation $lookup (this one seems new).

Here's how I tried, but not working at all.

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 );
        }
    })
chridam
  • 100,957
  • 23
  • 236
  • 235
Eric Turner
  • 41
  • 1
  • 5

1 Answers1

2

activity_id should be ObjectId data type. ObjectId documentation

If you want to use pupoluate, you must to use ref to the other schema. 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);

So the query such as :

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
   }
});
Loint
  • 3,560
  • 7
  • 26
  • 46
  • Thanks for the help. Do you mean I have to change my activity_id(value) to ObjectId("xxxxxxx")? Cuz I'm told that the activty_id is ruled. I can't change its value – Eric Turner Aug 29 '16 at 08:51
  • What do you mean about rule? Mongo auto provide primary key ( _id ) for you !. So you don't need define ``activity_id`` for activity collection. – Loint Aug 29 '16 at 08:58