0

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?

1 Answer 1

1

Using mongoose aggregate method and the async library, I managed to get it to work the way I want and need:

SchemaOne.aggregate([ { $match: { $and: [{'ancestor': ancestor }, { 'schemaTwo': { $exists: true } }] } }, { $group: { _id: '$schemaTwo' } }, { $limit: 15 }, { $sort : { 'created_at': -1 } } ], function(err, results) { // do something with err async.map(results, function(doc, callback) { SchemaTwo.findById(doc, function(err, result) { if(err) { return callback(err, null); } return callback(null, result); }); }, function(err, docs) { // do something with err // here I have my results the way I want }); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

How does this perform, when you do an aggregate first followed by findById loop? Are you still using this or improved upon this?