【发布时间】:2016-10-19 01:31:45
【问题描述】:
var PostSchema = new mongoose.Schema({
item: {
type: mongoose.Schema.ObjectId,
ref: 'item',
required: true
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
},
vote: {
type: Number,
default: 0
},
total: {
type: Number,
default: 0
},
awsPostKey: {type: String},
picture: {type: String, required: true}
});
var data = function(){
return Post
.find({})
.then(function(post){
return post;
})
};
var userId = //mongo objectId for current user
//postVote schema:
var PostVoteSchema = new mongoose.Schema({
post: {
type: mongoose.Schema.ObjectId,
ref: 'Post',
required: true
},
user: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true
},
vote: {
type: Number,
default: 0
}
});
//pass data from Post query to PostVote sum function:
PostVoteSchema.statics.sum = function (data, userId) {
var postIds = data.map(function (a) {
return a._id;
});
return PostVote
.aggregate(
[
{ $match: { 'post': {$in: postIds}}},
{ $group: { _id:'$post' ,vote:{$sum:'$vote'}}}
])
.execAsync()
.then(function(votes){
return votes;
//desired output to client, _id is for specific post
{_id: 5802ea4bc00cb0beca1972cc, vote: 3, currentUserVote: -1}
});
};
我成功地获得了具有相同 postId 的所有选票的总和。 现在,我想查看当前用户 (userId) 是否也对给定的帖子进行了投票,然后返回他们的投票方式(+1 或 -1)以及对特定帖子的所有投票的总和.
是否可以这样做,或者我必须在我的聚合管道之外执行此操作 - 在第二个查询中?不得不再次查询该集合似乎很费力。
【问题讨论】:
-
您能否也显示一些给定示例文档的预期输出?
-
确定,我会添加预期的 JSON
标签: mongodb aggregation-framework mongodb-aggregation