0

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.

  • first I think you're missing a '.' after $ - if you update using positional operator you need $.subitem syntax. Secondly you may be mixing up upserts (which is when you want to insert a top level document if it doesn't exist for update) and $addToSet which is $push to an array a new item (subdocument) if it doesn't already exist. Former probably has to do with lack of updates but latter suggests this is not a correct structure for what you want to achieve – Asya Kamsky Apr 28 '13 at 19:21
  • Thanks for the reply, the error I get when I change the syntax does indicate it's trying to create a duplicate "user" but I'm just not sure how to approach this. Also, I can't use $push or $addToSet because "inv" isn't an Array, it's a (sub)document type. – user1941621 Apr 28 '13 at 19:29
  • Can you include a document out of MongoDB that shows a typical record either before or after an update? For each user how do you represent if they have multiple items if it's not via an array? – Asya Kamsky Apr 28 '13 at 19:31

0 Answers0