我正在尝试使用find $ in数组在mongodb中增加一项,但是当数组中有相同项目(例如['apple','apple']
时,它应该增加两次,但对我而言,它只会增加一次) ,看看我的代码:
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');
}
});
}
});
答案 0 :(得分:0)
我知道已经有一段时间了,但这可能仍然对您(或其他人)有帮助,所以...
也许您可以尝试以下方法:
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 === //
}
});