使用增量循环功能

时间:2019-03-20 03:02:21

标签: node.js angularjs mongodb express mean-stack

我正在使用for循环,在增加数组中的项的同时执行某些功能

   $scope.newGetbloodcomponent = ['a','a','a']
   $scope.newBloodgroup = "A_positive";
 for(index = 0, len =  $scope.newGetbloodcomponent.length; index < len; index++){ 
            var userObject = {}; 
            var index,len;
            userObject.blood_component = $scope.newGetbloodcomponent[index];
            userObject.blood_group = $scope.newBloodgroup;

            Bloodinventory.addDecreaseinventory(userObject).then(function(data) {});

            }

然后在我的api.js中,我想增加数组中的每个项目:所以我想使用数组['a','a','a']在mongodb中查找并增加某个文档,但这仅是增加一次,这就是我所做的:

        var newValue = 1;
        var newGetbloodcomponent = req.body.blood_component; 
        var newBloodgroup = req.body.blood_group; 


        Bloodinventory.find({$and: [ {blood_component : { $in : newGetbloodcomponent}} ,{blood_group: { $in :newBloodgroup}}] }, function(err, bloodinventoryDocs) {

            for(let bloodinventory of bloodinventoryDocs) {
                bloodinventory.num_stock = bloodinventory.num_stock + newValue ;                        
                bloodinventory.save(function(err) {
                    if (err) {
                        console.log(err); 
                    } else {
                        console.log('success'); 
                    }
                });
            }  
        });

我的问题是,当在数组[a,a,a]中使用相同的项时,它将被读取一次,因此它只会增加一次,而不是增加三倍

样本文档:

_id:5c743847083f66292481c1b3
blood_group:A_positive
chapter:5c014c999cc48c3b0057988b
num_stock:12          //this should be 15 if the array is ['a','a','a']
blood_component:a
reserved_stock:0
remaining_stock:0
blood_type:A

0 个答案:

没有答案