1

I want to use a time log in my database entries and I want that the time is always taken from the server.

So far I set this up:

Meteor.methods({
    getTimeFromServer: function () {
        var serverTime = new Date().toLocaleTimeString();
            return serverTime;
    }
});

I want to use them like this:

Template.myTemplate.events({
    'click .btn': function(e) {
        var propsOfObject = {
            name: $('#idName').val(),
            email: $('#idEmail').val(),
            time: Meteor.call('getTimeFromServer')
            }
        Meteor.call('addItemToDataBase', propsOfObject)
    }
});

Can't figure out what I am doing wrong. I don't get any error messages. The 'time'-property is simply empty.

Moritz Schmitz v. Hülst
  • 2,260
  • 3
  • 24
  • 43

1 Answers1

3

First of all, your approach is not working because Meteor.call on the client is always asynchronous : it doesn't return anything immediately, you must provide a callback to fetch the result some time later.

More in this here : Meteor.methods returns undefined

I think you should get the server time directly in the insertion method instead of trying to fetch it from the server before inserting : it will save you a method call and it's simpler too.

client :

Template.myTemplate.events({
  'click .btn': function(e) {
    var propsOfObject = {
      name: $('#idName').val(),
      email: $('#idEmail').val()
    };
    Meteor.call('addItemToDataBase', propsOfObject)
  }
});

server :

Meteor.methods({
  addItemToDatabase:function(fields){
    check(fields,{
      name:String,
      email:String
    });
    //
    _.extend(fields,{
      time:new Date().toLocaleTimeString()
    });
    //
    MyCollection.insert(fields);
  }
});
Community
  • 1
  • 1
saimeunt
  • 22,472
  • 2
  • 53
  • 61