Keeping the schema as nested, pull your whole array out, traverse it to find the object you want, modify the field and set your whole array again (js doens’t guarantee array ordering so doing estate[1] is very fragile.
The document selector part ({_id:Meteor.userId(), "estate.index": 2} identifies the document (_id) and the position in the estate array we are targetting ("estate.index": 2).
The update part ({$set: {"estate.$.owned": 100}}) uses the $ positional operator to reference the array element we found and then sets the owned value to 100.
I’m creating a game where users can buy 3 different houses, and they can own how many they want. Maybe there is an easier way to store this data? Maybe in a new collection as mordax suggestions, however i dont understand his solution
The houses has its own fields, “price: 200, name: ‘kiosk’, userOwns: 10, income: 10”. For example.
I wish to print out the houses to the user using
{{#each realestate}}
{{price}}
{{name}}
etc, etc
{{/each}}
And allow the user to press a buy button on the site.
I got it all down but i couldnt figure out how to update the userOwns variable to the client view. I stored the houses in a json file, and i used 3 different variables in the user collection. thisUser.estate1 = 5, thisUser.estate2 = 10, etc. (But how would i show this in the view? It was in a different collection and how do you sync them up)
Maybe there is a simpler way to do this, i thought that would be to store the whole object at the user collection, but that seemed unnecessary complex?
Do you have any simpler suggestion? I appreciate it a lot, ive been stuck on this problem for a while
EDIT: This seems so hard to code, but for the user its very simple. They only want to see a list of houses, the price, how many they own, and the ability to buy them - and see it update in realtime
I wonder if there is any simpler solution, since @mordrax said it was a very complex and weird way to solve it, i explained my situation and im asking for your expert advice on how to solve this problem the best way
Well, updating an array element buried in a mongo document is neither difficult nor weird. The code I provided works. However, it will only work on the server, because the find component is not simply _id (this is a Meteor client restriction). The code could go in a Meteor method, for example and your client could call it to do the update.
Having said that, it may not be the optimum solution for your requirement, but I am still unclear as to how your application code and data is organised.
Can you provide a minimum repo which works where you’ve got it to work?
The package is just building an update query behind the scene. All the usual allow/deny rules apply. The update is done through minimongo, it doesn’t use a method or other mean to directly alter the server db.