1

Server Side Code:

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'});
  });
}

Client Side Code

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

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

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

The problem:

When in javascript console I type Messages.insert({'text' : 'test test test'}); or click the button, underneath which a database insertion call is written

I don't see a document inserted in mongo. Going to mongo console and doing show dbs shows messages (empty)

I have a few other questions, I have read through the meteor docs and also googled but I can't seem to find a clear answer to this:

  1. Why do I need to declare a collection in client as well as server code?
  2. I'm declaring collections inside Template.hello.greeting, what's the difference if I put it in if(Meteor.isClient) block directly.
  3. Is any plans of adding some app directory structure in meteor like rails? where models and templates are separate? I'm not talking about express.js

Thanks.

4

1 回答 1

11

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

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

或者首选方法是创建一个服务器方法来插入文档,并使用 Meteor.call().

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

更新:流星 > 0.9.1

在 Meteor 中创建集合现在是:

Messages = new Mongo.Collection("Messages")

代替:

Messages = new Meteor.Collection("Messages")
于 2013-04-09T08:17:29.953 回答