Charlie
Charlie

Reputation: 41

Adding associative document _id to user.profile key in Accounts.onCreateUser()

I am trying to insert a document id into the user.profile key when in Accounts.onCreateUser(), as to be able to associate a separate document in a different collection (holding user information) to a user when they are signed in.

//serverMain.js
Accounts.onCreateUser(function(options,user){
  var userId = user._id;
  user.profile = user.profile || {};
  _.extend(user.profile, {profComp: false});
  insertShopObject(userId);
  return user;
});

The insert I am using is

insertShopObject(userId);

This inserts a new document with pre-set fields into a separate collection called ‘ShopList’, I have passed in the userId as a parameter which is added as a field into the ‘ShopList’ collection. I can see from the server console that the document _id is returned when I call insertShopObject(userId);

enter image description here

I somehow want to catch that id when the document is inserted and add it into the user.profile key on user creation like so

_.extend(user.profile,{shopId: <-- ?-->})

Here is the insertShopObject function, I have tried returning instead of console logging the ‘result’ into a holding variable with no luck.

   //serverMain.js

    insertShopObject = function(userId){
    var newShop = {
      //pre-set fields.....
      }
    ShopList.insert(newShop, function(error,result){
        if(error){console.log(error);}
        else {console.log(result)}
     });
}

Upvotes: 0

Views: 36

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20246

You need to make the insert synchronous for this to work. Omit the callback from ShopList.insert() and do:

insertShopObject = function(userId){
  var newShop = {
    //pre-set fields.....
  }
  var shopId = ShopList.insert(newShop);
  return shopId;
}

Upvotes: 1

Related Questions