Not sure why this isn't working, I've tried a few different variations of syntax, but no go. I'm also unsure if having an update inside a for loop is a good idea.
Basically I'm updating a user's inventory by passing an object that contains two arrays (item[], and item_qty[]) that resembles as such:
var itemset = {}
itemset.item['Gold','Silver','Bronze']
itemset.item_qty[1,3,5]
itemset.qty = itemset.item.length
and the arrays can have varying lengths as such:
var itemset = {}
itemset.item['Platinum','Bronze']
itemset.item_qty[1,1]
itemset.qty = itemset.item.length
The goal is to keep adding to a user's inventory item quantity if the item exists, or add it (along with the quantity) if it doesn't exist. So using the two updated examples, the user will have Platinum(1), Gold(1), Silver(3) and Bronze(6) after they have both passed through the function.
The schema for the USER is:
var UserSchema = new mongoose.Schema({
name: {type: String, required: true},
mail: {type: String, required: true},
inv: {
item: {type: String},
iqty: {type: Number}
}
})
And here is the function:
function addInv(userId,itemset) {
for(i=0;i<itemset.qty;i++){
console.log('Updating:' + itemset.item[i])
db.User.update(
//Criteria
{
_id: userId,
inv: {item: itemset.item[i]}
},
{
$set:
{
inv:
{
'$item': itemset.item[i],
$inc: {'$iqty': itemset.item_count[i]}
}
}
},
{upsert:true},
function(err,i)
{
console.log('Error: ' + err)
console.log('Db: ' + i)
}) //End Update()
}
}
This works, in the sense of syntax, but it never updates the data...
I'd also like to see if there's a way to do this without having the for loop & multiple db calls.