1

I know how to update objects within an array like the following:

db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

But, im trying to currently update a object.

model:

  boats: {
        cash: {type: Number, default: 0},
        amount: { type: Number, default: 0}
    },
    murder: {
        attempts: {type: Number, default:0},
        failed_attempts: {type: Number, default:0},
        successfull_attempts: {type: Number, default:0},
        cash: {type: Number, default: 0},
        amount: { type: Number, default: 0}
    },
    orgcrime: {
        cash: {type: Number, default: 0},
        amount: { type: Number, default: 0}
    },

i have a variable called type that contains the word i want to update, for example: murder . I also have a variable called num, that will be updated value.

CurrentStats contains the full model result.

i get the types object by doing:currentStats[type]` , but how can i update it?

i tried with:

var x = {};
        x[type].cash = num;
        x[type].amount = 1;

and {$inc: x} , but that wouldnt work.

How would i go about this?

1 Answer 1

1

You mean to actually form the field names using "Dot Notation", by concatenating the name of the key:

var type = "murder";

var x = { };

x[type + ".cash"] = 1;
x[type + ".amount"] = 2;

db.bar.update({},{ "$inc": x });

Modern ES6 Notation also allows other forms like :

db.bar.update(
  {},
  { 
    "$inc": {
      [type + ".cash"]: 1,
      [`${type}.amount`]: 2
    }
  }
);    

Either way forms

{
  "$inc": {
    "murder.cash": 1,
    "murder.amount": 2
  }
}

Which is what you want to update those properties and only those properties when making changes to the document.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.