2016-03-22 5 views
0

は、私が2つの以下のスキーマを持っていると仮定し、その結果クエリから重複を削除します。マングース -

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

私は何をしたいことは次のとおりです。提供したものと同じ祖先を持つすべてのSchemaOne文書について、SchemaTwo年代を返すにクエリの結果が重複を返すべきではないことを考慮に入れて、関連するヘッドライン(存在する場合)は、SchemaOnecreated_atフィールドの降順でソートされた15個の結果に限定する必要があります。

私は、次の操作を実行しました:

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

をしかし、そうすることによって、私はまだ、すなわち、私は同じSchemaTwo文書に関連付けられた複数のSchemaOne書類を持って、重複した結果が得られます。

これを解決する方法を教えてもらえますか? mongoose aggregate方法とasyncライブラリを使用して

答えて

1

は、私はそれが私が望むようにと必要性を動作させるために管理:

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

あなたが最初findByIdループが続く集計を行うとき、これは、実行しない方法は?あなたはまだこれを使用しているのですか、これを改善していますか? – runios