Mongoose返回更新的文档,文档未在数据库中更新

时间:2018-01-12 09:25:15

标签: javascript mongodb mongoose

我在一个算法上挣扎着在流动的民主制度中委派选票。我的问题是Mongoose有一个非常意外的行为。在使用.findOneAndUpdate时,它会返回一个更新的文档(在我的情况下,我想要权重= 0),但是如果我之后查看数据库,则文档没有更新。

这是代码:     Vote.count({propId:propId,delegation:true},function(err,voteNumber){

var maxDelegation = voteNumber;

for(var d=1; d<maxDelegation+1; d++){

        Vote.find({propId: propId, delegation: true, weight: d}, function(err, specWeightVotes){

            for (var i = 0; i < specWeightVotes.length; i++) {

                console.log(specWeightVotes[i].content);

                // Add the weight d, aka the weight of a vote to the delegated voter
                Vote.findOneAndUpdate({propId: propId, voter: specWeightVotes[i].content }, { $inc: { 'weight': specWeightVotes[i].weight }}, function (err) {
                    if (err) {
                        console.log("Ca bug.");
                    }
                });

                //Put weight as zero for the ones who have delegated
                Vote.findOneAndUpdate({_id: specWeightVotes[i]._id}, { $set: { 'weight': 0 }}, {new: true}, function (err, vote) {
                        if (err) {
                            console.log("Ca bug 2.");
                        }
                        console.log(vote);
                });
            }
        });
    }
    console.log("I have delegated all votes");
});

在第二个.findOneAndUpdate中,console.log的结果是:

{
_id: '5a587a96445e1900474d6ae3',
propId: '5a587a84445e1900474d6ade',
voter: 'someVoterID',
delegation: true,
content: 'someOtherVoterID',
weight: 0,
__v: 0 }

预期结果如何。但是,在数据库中,在执行函数时,权重保持为1,如果它更高,则为X:

{
_id: '5a587a96445e1900474d6ae3',
propId: '5a587a84445e1900474d6ade',
voter: 'someVoterID',
delegation: true,
content: 'someOtherVoterID',
weight: 1,
__v: 0 }

作为一个额外的信息,没有任何代表团会对给定的文件加分。

1 个答案:

答案 0 :(得分:0)

尝试按照代码告诉我结果。

 var maxDelegation = voteNumber;

 for(var d=1; d<maxDelegation+1; d++){

   let specWeightVotes = Vote.find({propId: propId, delegation: true, 
   weight: d}).map(function(k){
    return k;
   });

   for (var i = 0; i < specWeightVotes.length; i++) {

    console.log(specWeightVotes[i].content);

    // Add the weight d, aka the weight of a vote to the delegated voter
    Vote.findOneAndUpdate({propId: propId, voter: 
    specWeightVotes[i].content }, { $inc: { 'weight': 
    specWeightVotes[i].weight }}, function (err) {
       if (err) {
          console.log("Ca bug.");
       }
    });

    //Put weight as zero for the ones who have delegated
    Vote.findOneAndUpdate({_id: specWeightVotes[i]._id}, { $set: { 
    'weight': 0 }}, {new: true}, function (err, vote) {
       if (err) {
          console.log("Ca bug 2.");
    }
          console.log(vote);
    });
   }
  }
 console.log("I have delegated all votes");
});