Creating field based on userId

Hi, I’m new to Meteor and excited to get started. Got a lot of the basics down on my own, but hit a roadblock and could use some help.

I have a list of life values that users click to assign its importance. So there is a preset list of values that load for all users share. The trouble I have is how to create an indicator for each user so that only their assignments show up on a list.

I understand that if users each created their own item you could search through a field that shows it was created by them.

var currentUserId = Meteor.userId();
DB.insert ({}, {$set {createdBy: currentUserId}});

But how do you create a field based on the userId instead? This way even though the same list of life values is shared between all users I can pull only the life values that that user has assigned.

var currentUserId = Meteor.userId();
DB.insert ({}, {$set {currentUserId: 1}});

When I try this it just creates a field called currentUserId instead. Maybe there is another way, but I’m not really sure how. Any help is appreciated!

You would have to build your $set modifier programmatically:

const currentUserId = Meteor.userId();
const modifier = {
  $set: {}
};
modifier.$set[currentUserId] = 1;
DB.insert({}, modifier);

Thanks for the help hwillson. I sort of figured it out, but can I ask you how this works? It helps when I understand what’s going on so I can use it in the future.

I get that the square brackets set a key and value pair, but why does it have to be done this way in order to be inserted into Mongo?

This doesn’t really have anything to do with Mongo; it’s more of a limitation of javascript (well, old limitation - this can now be worked around with ES2015). Javascript used to prohibit dynamic object property names defined using { … } syntax. Using the object[name] = value approach provides one way to work around this. That being said in ES2015 you can now do this a bit differently, so something like the following would also work:

const currentUserId = Meteor.userId();
DB.insert({}, {
  $set: {
    [currentUserId]: 1
  }
});

Ahh! That makes everything a lot easier! Now I can use Javascript variables in the database. Thanks for the help!

I get that different languages have to be ‘translated’ to speak to each other. Always a bit tough to figure out how though…