简体   繁体   中英

Meteor.js Collection not being created in mongo

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.

You need to create the MongoDB collection in a global scope like outside of both the isClient and isServer scopes. So remove Messages = new Meteor.Collection("Messages") from that helper function and place it in global scope.

You cannot perform insertion directly through client, as meteor doesn't allows database insertion from client code. If you still want to insert/update from client, you must define database rules for client, see docs .

Or the preferred way is to create a server method to insert document, and call it from client using Meteor.call() .

Creating collections inside Template.hello.greeting doesn't makes any sense, since the collections are used to store data on server that is accessible from client.

Update: Meteor > 0.9.1

Creating collections in Meteor is now:

Messages = new Mongo.Collection("Messages")

instead of:

Messages = new Meteor.Collection("Messages")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM