首页 文章

Meteor.js集合没有在mongo中创建

提问于
浏览
1

服务器端代码:

if (Meteor.isClient) {
  Meteor.subscribe("messages");
  Template.hello.greeting = function () {
    Messages = new Meteor.Collection("messages");
    Stuff = new Meteor.Collection("stuff");
    return "Welcome to feelings.";
  };

  Template.hello.events({
    'click input' : function () {
      // template data, if any, is available in 'this'
      if (typeof console !== 'undefined')
        var response = Messages.insert({text: "Hello, world!"});
        var messages = Messages.find
        console.log("You pressed the button", response, Messages, Stuff);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
    Messages = new Meteor.Collection("messages");
    Messages.insert({'text' : 'bla bla bla'});
  });
}

客户端代码

<head>
  <title>Test</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <h1>Hello World!</h1>
  {{greeting}}
  <input type="button" value="Click"/>
</template>

问题:

在javascript控制台中我输入Messages.insert({'text':'test test test'});或单击按钮,在该按钮下面写入数据库插入调用

我没有在mongo中看到插入的文档 . 去mongo控制台和做show dbs显示消息(空)

我还有其他几个问题,我已经阅读了流星文档并且也用Google搜索了,但我似乎无法找到一个明确的答案:

  • 为什么我需要在客户端和服务器代码中声明一个集合?

  • I 'm declaring collections inside Template.hello.greeting, what' s如果我把它放在if(Meteor.isClient)直接阻止的区别 .

  • 是否有任何计划在流星像rails中添加一些应用程序目录结构?模型和模板是分开的?我不是在谈论express.js

谢谢 .

1 回答

  • 11

    您需要在全局范围内创建MongoDB集合,例如 isClientisServer 范围之外 . 因此,从该帮助函数中删除 Messages = new Meteor.Collection("Messages") 并将其置于全局范围内 .

    您不能直接通过客户端执行插入,因为meteor不允许从客户端代码插入数据库 . 如果您仍想从客户端插入/更新,则必须为客户端定义数据库规则,请参阅docs .

    或者首选方法是创建一个插入文档的服务器方法,并使用 Meteor.call() 从客户端调用它 .

    Template.hello.greeting 中创建集合没有任何意义,因为集合用于在可从客户端访问的服务器上存储数据 .

    更新:流星> 0.9.1

    现在在Meteor中创建集合:

    Messages = new Mongo.Collection("Messages")
    

    instead of:

    Messages = new Meteor.Collection("Messages")
    

相关问题