如何在投票分组并在相同的聚合函数中进行投票之前检查当前用户的投票

时间:2016-10-19 01:31:46

标签: mongodb aggregation-framework mongodb-aggregation

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)以及所有投票的总和。具体职位。

是否可以在第二个查询中执行此操作,或者我必须在聚合管道之外执行此操作?只是再次查询集合似乎很有可能。

1 个答案:

答案 0 :(得分:0)

是的,这是可能的。在 $group 管道中,您可以使用 $cond 运算符作为提供 $sum 累加器操作员。例如:

ForEach ($instance in Get-Content "C:\servers\List.txt") 

{ 
$local = Get-Location;
$final_local = "C:\BKP";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        New-Item -ItemType Directory -Force -Path "$final_local";
        cd $final_local;

    }

    ## if path already exists
    ## DB Connect

}

}