【问题标题】:Mongoose - Remove duplicates from query resultsMongoose - 从查询结果中删除重复项
【发布时间】:2016-03-22 17:01:11
【问题描述】:

假设我有以下两种模式:

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

但是这样做,我仍然会得到重复的结果,即,我将有多个 SchemaOne 文档与同一个 SchemaTwo 文档相关联。

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案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
      }); 
    });
    

    【讨论】:

    • 当您先进行聚合然后执行 findById 循环时,它的执行情况如何?你还在使用这个还是改进了这个?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2017-07-02
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    相关资源
    最近更新 更多