Setting a server variable to data held in a mongo collection

For my application, I have to make an HTTP.call to get a session ID. I need to store this session ID into a mongo collection, which I am doing like this.

if (Meteor.isServer) {
  sessionDB = new Mongo.Collection("sessionID");
  HTTP.call( 'GET', 'http://mycalltosomeapi.svc/json/whatever', {
  }, function( error, response ) {
if ( error ) {
  console.log(error);
} else {
  sessionDB.insert({
sessionId: response.data.session_id,
date_inserted: new Date()
  });
}

}

how do I grab the most recent entry of my mongo stored ā€˜sessionIdā€™ and put that into a variable so I can make other calls? I tried doing it like this but had no luck.

var sessionId = sessionDB.findOne({}, {sessionId: 1}).sort({ā€œdate_insertedā€:-1}).limit(1);

Any help is greatly appreciatedā€¦ been researching for an hour and being new to mongo in general does not help.

You are trying to mix Meteor syntax with MongoDB syntax. What you want is:

var sessionId = sessionDB.findOne({}, {fields: {sessionId: 1}, sort: {date_inserted: -1}}).sessionId;

Notes: findOne gives you the limit: 1 for free and returns an object (so you need to explicitly reference the sessionId).

Check the docs for more information.

1 Like

This worked. Thanks!

1 Like

@robfallows Not sure if I should post this here, or make a new threadā€¦ It follows along the same-ish issue with my sessionIdā€¦ This works beautifully on my localhost, but I tried deploying it for testing and it crashes with a 503, saying that sessionId is not definedā€¦ Using the method that I posted below, is sessionId not global for some reason? Or is there some type of issue with deploying to xxx.meteor.com as of now?

 setSession();
  Meteor.setInterval(setSession, 60000);
  function setSession() {
  HTTP.call( 'GET', 'http://api.smitegame.com/smiteapi.svc/createsessionjson/' + devId, {
  }, function( error, response ) {
if ( error ) {
  console.log(error);
} else {
  sessionDB.insert({
sessionId: response.data.session_id,
date_inserted: new Date()
  });  
}
  });//ends call
  assignSession();
}
function assignSession() {
  var options = {
fields: {sessionId: 1, _id: 0},
sort: {date_inserted: -1}
  };
  var sessionIdb4 = sessionDB.findOne({}, options);
  sessionId = sessionIdb4.sessionId;
}

I tried to run the contents of the assignSession() function inside of my setSession() function but that gave an error on my localhost. For some reason, doing it this way worksā€¦On my localhost

Your dev database will not be deployed along with your code. Perhaps that is the reason?

That would make sense since I am storing my sessionIdā€™s thereā€¦ Is there a work around for that? I must store them, and get a new one every x minutes.

I managed to find a work around (for anyone who this same problem might apply to). I ended up using the Meteor.startup() function. I declared my database in there along with my global variables that I use through-out the application.