Mongoose - 从查询结果中删除重复项

时间:2016-03-22 17:01:11

标签: node.js mongodb mongoose

假设我有以下两种模式:

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标题(如果有),考虑到查询的结果不应返回任何重复项,并且应限制为按SchemaOne的{​​{1}}字段的降序排序的15个结果。

我开始做以下事情:

created_at

但是通过这样做,我仍然会得到重复的结果,即我将有多个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 }); 文档与同一个SchemaOne文档相关联。

你能帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

使用mongoose aggregate方法和async库,我设法让它以我想要的方式工作:

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
  }); 
});
相关问题