Search code examples
meteoriron-router

getting some part of URL


I'm trying to get the end part of this URL (in the sever side):

http://localhost:3000/insAds/D79htZY8DQ3YmcscE

I mean I want to get this string:

D79htZY8DQ3YmcscE

there is a similar question: How to get the query parameters in Iron-router?

but non of the answers can't help me! because I have no query params in the URL.

I know these codes gives me the string that I want:

this.params.id

and

Router.current().params.id

but these codes works only in client side! I want to get that string in the server side!

finally I'm trying to get that string and use here:

Ads.before.insert(function(userId, doc) {
    //console.log(this.params.id);
    doc._categoryId = this.params.id;
    doc.createdAt = new Date();
    doc.createdBy = Meteor.userId();
});

Solution

  • You can use Router.current().params or this.params like this

    Router.route('/insAds/:id', function () {
        console.log(this.params.id); // this should log D79htZY8DQ3YmcscE in console
    });
    

    Check the third example in Quick Start section of iron router documentation

    EDIT: Based on our chat,

    Your hook is

    Ads.before.insert(function(userId, doc) {
        //console.log(this.params.id);
        doc._categoryId = this.params.id;
        doc.createdAt = new Date();
        doc.createdBy = Meteor.userId();
    });
    

    Change it to

    Ads.before.insert(function(userId, doc) {
        doc.createdAt = new Date();
        doc.createdBy = Meteor.userId();
    });
    

    And then define meteor method in server like this

    Meteor.methods({
        'myInsertMethod': function (id) {
             Ads.insert({
                 _categoryId: id
             });
        }
    });
    

    Call this from client side like this

    Meteor.call('myInsertMethod', Router.params().id, function (err, res) { 
        console.log (err, res);
    });