Suppose I have the two following schemas:
var SchemaOne = new mongoose.Schema({ created_at: { type: Date }, schemaTwo: { type: mongoose.Schema.Types.ObjectId, ref: 'SchemaTwo' }, ancestor: { type: mongoose.Schema.Types.ObjectId, ref: 'SchemaOne' } }); var SchemaTwo = new mongoose.Schema({ headline: { type: String, required: true } }); What I would like to do is: for every SchemaOne document with the same ancestor as one provided, return the SchemaTwo's headline to which they are associated (if any), taking into account that the results from the query should not return any duplicates and should be limited to 15 results sorted by descending order of SchemaOne's created_at field.
I started doing the following:
SchemaOne .find({ 'ancestor': ancestor }) .sort({ 'created_at': -1 }) .populate({ path: 'schemaTwo', select: 'headline', options: { limit: 15 } }) .exec(function(err, docs) { // do something with the results }); But by doing so, I will still get duplicated results, i.e., I will have multiple SchemaOne documents associated with the same SchemaTwo document.
Can you give me a helping hand on how to solve this?