2017-08-21 62 views
1

我欣赏一些帮助。我正在用express和mongodb(v3.4.4)做一个api rest,使用猫鼬(v4.10.5)。我需要做一个聚合操作,但我没有处理它。我给你看一些代码。该模型(它有更多的属性,但我已经离开它简单):如何使聚合+填充猫鼬

const CategoryModel = mongoose.model('Category', new Schema({ 
    slug: { type: String, unique: true, lowercase: true, index: true }, 
    description: String 
})); 

const MyModel = mongoose.model('MyModel', new Schema({ 
    category: { type: Schema.Types.ObjectId, ref: 'Category' }, 
    other: [{ type: Schema.Types.ObjectId, ref: 'Other' }], 
    times_count: { type: Number, default: 0 } 
})); 

重要的是,我很感兴趣的MyModel填入category场,不other场。

假设CategoryMyModel具有良好的记录。请求:

MyModel.aggregate([ 
    { 
    $group : { 
     _id : '$_id', 
     times: { $sum: '$times_count' } 
    } 
    }, 
    { 
    $limit: 5 
    } 
]).limit(5).exec().then((data) => { 
    console.log(data); 
}).catch((err) => { 
    console.error(err); 
}); 

data是正确的,有5条记录,但不包括category。现在,我试着用:

MyModel.aggregate([ 
    { 
    $group : { 
     _id : '$_id', 
     times: { $sum: '$times_count' } 
    } 
    }, 
    { 
    $limit: 5 
    }, 
    { 
    $lookup: { 
     from: 'Category', // I tried with 'Categories' and 'categories' 
     localField: 'category', 
     foreignField: '_id', 
     as: 'category' 
    } 
    }, 
    { 
    $unwind: '$category' 
    } 
]).limit(5).exec().then((data) => { 
    console.log(data); 
}).catch((err) => { 
    console.error(err); 
}); 

现在data是空的。我设置了mongoose.set('debug', true);以及它们看起来正确的操作,包括最后的操作aggregate,但是数据是空的...

我不知道我是否解释得很好。显然有一些我不完全理解。提前致谢。

回答

1

我在objs中得到所需的记录,问题是我只带有_id和times属性,而我需要填充类别。

这是关于正确的,因为你没有明确地添加舞台加入其他集合。

我已经尝试添加$项目到$组,但没有后聚集。

简而言之,$project用于包含和排除使用一个集合而不是加入的新字段。

您在寻找$lookup这是用于加入一个集合与另一个。当您加入一个新的集合时,每个文档将有一个新的数组字段,其中包含来自其他集合的“已加入”文档。

在你的情况下,你的新数组字段将有另一个集合中的一个文档,所以你可能也想要$unwind

MyModel.aggregate([ 
    { 
     $group : { 
      _id : '$_id', 
      times: { $sum: '$times_count' }, 
      category: { $first: '$category' } 
     } 
    }, 
    /* 
    { 
     $limit: 5 
    }, 
    */ 
    { 
     $lookup: { 
      from: 'Categories', 
      localField: 'category', 
      foreignField: '_id', 
      as: 'category' 
     } 
    }, 
    { 
     $unwind: '$category' 
    } 
]).exec(...); 

在你最初的问题而言,尝试取消注释上面,而不是第二阶段在你第一次例如使用limit(5)

+0

谢谢,但不工作。我试着用'from:'Category'','localField:'category''和其他组合,我在数组中包含'$ limit',并且没有'$ unwind' ......总之,有几十个组合。另外,为什么需要光标?我不明白。请注意,我要填充的字段是“MyModel”的“类别”,而不是“_id”。再次感谢。 – lmfresneda

+0

@LuisMiguelF。啊,你说得对,它应该是'category'。你不应该需要'cursor()'如我的例子所示。我还会设置[debug on](http://mongoosejs.com/docs/faq.html#enable_debugging)来查看任何查询。用类别模式编辑您的问题。你是否也在运行MongoDB v3.2或更高版本? – Mikey

+0

对不起@Mikey,光标是我的错,我在这个测试中用Mockgoose代替Mongoose(尽管我不知道为什么Mockgoose需要一个游标)。现在,我只使用猫鼬,我会编辑我的问题。还是不行... :( – lmfresneda