本文介绍了对于 let,如果数组中有相同的项目,则不递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 find $in 数组增加 mongodb 中的一个项目,但是当数组中有相同的项目时,例如 ['apple','apple'] 它应该增加两次但就我而言,它只增加一次,看看我的代码:

I'm trying to increment an item in my mongodb using find $in array, but when there is a same item in an array for example ['apple','apple'] it should increment twice but for my case, it only increment once, look at my code:

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

 Bloodinventory.find({ blood_component : { $in : newGetbloodcomponent} ,blood_group: { $in :newBloodgroup},chapter: { $in: [id] }}, 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');
                    }
                });
            }
        });

推荐答案

我知道这已经有一段时间了,但这可能仍然对您(或其他人)有帮助,所以...

I know this has been a while, but this might still help you (or maybe someone else), so...

也许你可以试试这个:

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

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

    for(let bloodinventory of bloodinventoryDocs) {
        // === change starts here === //
            // filter into a new array all the places where this particular blood component occurs
            let all_occurences = newGetbloodcomponent.filter(function(b){
                return b === bloodinventory.blood_component;
            });

            // to avoid incurring unnecessary processing and/or database costs, only continue if an occurence was actually found
            if(all_occurences.length > 0){
                // increment it by that amount (which will be the number of items filtered into the array)
                bloodinventory.num_stock = bloodinventory.num_stock + all_occurences.length;
                // ^^ you could also write this as 'bloodinventory.num_stock += all_occurences.length;'

                bloodinventory.save(function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log('success');
                    }
                });
            };
        // === change ends here === //
    }
});

这篇关于对于 let,如果数组中有相同的项目,则不递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 15:52
查看更多