Seperate publish function our of schema and into s

2019-09-14 06:51发布

问题:

I'm trying to update my application to utilise Meteors suggested file structure and I'm having trouble separating the publish function from the schema file. the file structure I'm trying to use is

imports/
  api/
    profile/                     
      server/
        publications.js
      Profile.js  

When I combine the publish function into the Profile.js schema file the publish function works and the data flows through to the client however when I separate them I'm unable to get it to publish. Can someone please show me how to separate the publish function and schema correctly.

Path: imports/api/profile/Profile.js

import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { AddressSchema } from '../../api/profile/AddressSchema.js';
import { ContactNumberSchema } from '../../api/profile/ContactNumberSchema.js';

export const Profile = new Mongo.Collection("profile");

Profile.allow({
  insert: function(userId, doc) {
    return !!userId;
  },
  update: function(userId, doc) {
    return !!userId;
  },
  remove: function(userId, doc) {
    return !!userId;
  }
});

var Schemas = {};

Schemas.Profile = new SimpleSchema({
  userId: {
    type: String,
    optional: true
  },
  firstName: {
    type: String,
    optional: false,
  },
  familyName: {
    type: String,
    optional: false
  }
});

Profile.attachSchema(Schemas.Profile);

if (Meteor.isServer) {
  Meteor.publish('private.profile', function() {
    return Profile.find({});
  });
}

Path: client/main.js

Template.main.onCreated(function() {
    this.autorun(() => {
        this.subscribe('private.profile');
    });
});

回答1:

This should work if you import the collection & make sure your publications are being imported to your server:

Path: /imports/api/profile/server/publications.js

import { Profile } from '/imports/api/profile/profile';

Meteor.publish('private.profile', function() {
    return Profile.find({});
});

You need to make sure you are importing your publications file to the server too. No files in the /imports directory are loaded unless they are imported to the server. The way we do this is import all of our publications and methods etc to a file in our /imports/startup/server directory and then we import that file to the actual meteor server.

So you need to import the publications in your /imports/startup/server/index.js file

Path: /imports/startup/server/index.js

import '/imports/api/profile/server/publications';

And finally you need to make sure your startup/server/index.js is being imported to the server

Path: /server/main.js

import '/imports/startup/server';

If this is confusing you I recommend you read TheMeteorChef's awesome article about the imports directory here: https://themeteorchef.com/tutorials/understanding-the-imports-directory

Also, this may seem complicated but stick with it and you'll understand it soon!