Iron-Router 在路由运行前检查文档是否存在

Iron-Router checking document existence before route runs

我有一个基本的聊天室应用程序,您可以在其中从调用此方法的主页创建一个房间:

createNewRoom: function (){
    //Room containers unique ID for the object
    var room = Rooms.insert({
        createdAt: new Date()
    });
    return room;
},

房间布置如下:

Router.route('/rooms/:_id', {
    name: 'room',
    template: 'chatRoom'
});

我正在尝试进行设置,这样您就不能随便输入任何随机 ID 就可以得到一个房间,它必须已经存在。所以我创建了这个 iron-router 钩子:

var checkRoomExists = function() {
    var room = Rooms.findOne({_id : this.params._id});
    if(typeof(room) == "undefined"){
        Router.go('home');
    }
    else {
        this.next();
    }
}

Router.onBeforeAction(checkRoomExists, {
    only : ['room']
});

roomcheckRoomExists 中总是 returns 未定义,即使我在其他地方用相同的 _id 测试完全相同的语句并且房间存在。因此,如果我将 link 发送给其他人,即使房间存在,它也会重定向。这是错误的挂钩类型还是有更好的方法来实现这一点?'

编辑一些附加信息: 这是第一次创建房间的代码:

Template.home.events({
    'click #create-room' : function(event){
        event.preventDefault();

        Meteor.call('createNewRoom', function(error, result){
            if (error){
                console.log(error);
            }else {
                Session.set("room_id", result);
                Router.go('room', {_id: result});
            }
        });
    }
});

如果我尝试在之后使用完整的 link,例如 http://localhost:3000/rooms/eAAHcfwFutRFWHM56,它不起作用。

I am trying to avoid users going to some random ID like localhost:3000/rooms/asdasd if a room with that ID doesn't already exist.

如果你想这样做,你可以按照下一个。

在布局配置中添加这个。

Router.configure({
  layoutTemplate: 'layout',
  loadingTemplate: 'loading',
  notFoundTemplate: 'notFound' //add the notFoundTemplate.
});

和这个简单的 onBeforeAction.

Router.onBeforeAction('dataNotFound', {only: 'room'});

像这样创建一些示例模板。

<template name="notFound">
 <span> Dam this route don't exist <a href="/">go back to home</a>
</template>

选项

我不确定这是否仍然有效,但您可以在 routes.js js

的最后定义它
this.route('notFound', {
  path: '*' //this will work like the notFoundTemplate
});

注意

如果您没有布局模板,请像这样使用。

Router.route('/rooms/:_id', {
    name: 'room',
    notFoundTemplate: 'authorNotFound',
    template: 'chatRoom'
});