understand new mongo id and use it with iron-router

前提是你 提交于 2019-12-04 15:01:35

问题


i have a simple post route that looks for the post _id. The problem is that the pathFor helper creates a path like this:

ObjectID("52e16453431fc2fba4b6d6a8")

I guess the mongoDB insertion as been changed and now the _id object holds another object inside it called _str.

Here is my route:

this.route("post", {
        path: "/post/:_id",

        waitOn:function(){
            NProgress.start();
            Meteor.subscribe("Teams");
        },

        before: function () {
            NProgress.done();
        },

        data: function () {
            return Posts.findOne({_id: this.params._id});
        }
    });

Currently, it creates an href like :

 post/ObjectID("52e16453431fc2fba4b6d6a8")

clicking on it opens a url

post/ObjectID("52e16453431fc2fba4b6d6a8") 

However, I get the "NotFound" template instead of the post.

How can I fix this?


回答1:


You need to change the pathFor 'post' to pass the hex representation of the ObjectId 52e16453431fc2fba4b6d6a8 instead of ObjectId('52e16453431fc2fba4b6d6a8')

Try something like this pathFor 'post' _id=this._id.toHexString

Once you are passing the hex string, you can use this in your router

return Posts.findOne({ _id: new Meteor.Collection.ObjectID(this.params._id)});




回答2:


Can you try this:

this.route("post", {
    path: "/post/:stringId",

    waitOn:function(){
        NProgress.start();
        Meteor.subscribe("Teams");
    },

    before: function () {
        NProgress.done();
    },

    data: function () {
        Post = Posts.findOne({_id: Meteor.ObjectId(this.params.stringId)});
    }
});

Now when you go to post/52e16453431fc2fba4b6d6a8 you should be able to see the correct post.

I am actually planning on using iron-router and objectid's in my application and thinking that this pattern would work.

I have not tried it yet, but let me know if there is a problem and I'll create a small test app to work it out.



来源:https://stackoverflow.com/questions/21317621/understand-new-mongo-id-and-use-it-with-iron-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!