Inserting a dynamic key into mongo


Does anybody know how to insert a key name from a variable / dynamic key into mongodb?

i want to create a simple object that the key name is the facebook id of the user and the value is the meteor user id. i have both, just not sure how to enter the key name

its a method i call on the server :

mappingUsers(facebookId) {
    UsersMap.insert({facebookId: this.userId});

how should i wrap / what to put instead on the facebookId in the insert function?


1 Like

Like this?

UsersMap.insert({[facebookId]: this.userId});

I am not sure what you’re trying to achieve, but this is what I infer from your statement. You have a user with a Meteor account _id and you want to associate this _id with their Facebook ID.
Here’s how you should do this:

First Method: Associate the FacebookID via the profile object. Though usually not advisable for security reasons. I have used this method successfully

Meteor.users.update({_id: Meteor.userId()}, {$set: {"profile.facebookid": facebookId}});

And if you already use the Facebook SDK for meteor, the FacebookID of the user should be associated already in the services section of the user account object.

Second Method:

mappingUsers(facebookId) {
    UsersMap.insert({fbId: facebookId, userId: this.userId});

Your choice…


hi, thanks, but im asking something else…

i want to create a separate collection which is for me to index my facebook ids and meteor ids.

basically, i want to create an array of objects, on which the keys are the facebook ids, and the values are the meteor ids.

UsersMap = [
{facebookId: meteorId},
{facebookId: meteorId},
{facebookId: meteorId}

so im not sure how to pass the facebook id as a dynamic key

if i wrap the key in [] it will make it dynamic and take the value from a var?

Yup, it’s a feature of ES2015.

1 Like


it helps a lot :slight_smile:

Suggestion: Per schema design principles for Mongo collections and future performance considerations, I suggest you consider de-normalizing the collection instead of pushing the Facebook IDs into an array. Searching through the userMaps collection could bring performance issues as the collection increases in size.

ohh, true, didnt think about it.

cool, will do that,

thanks a lot!!!

yeah putting it in user profile is probably a good idea

You are awesome! Just what I needed