简体   繁体   中英

Connecting an Orion-generated model to Meteor app

I used orion generate model to create a model called Events. I then inserted into that model in the Mongo DB console. I am not able to access that model from elsewhere because when I try to instantiate a Collection object, I am told that a model called Events already exists, which it does because my Events.js file looks as follows:

Events = new Mongo.Collection('Events');

Events.attachSchema(
new SimpleSchema({
    name: {
        type: String
    },
    location: {
        type: String
    },
    dateTime: {
        type: Date
    },
    description: {
        type: String
    },
    eventType: {
        type: String
    },
    createdAt: {
        type: Date,
        denyUpdate: true
    }
})
);

My header.js file looks as follows:

var Events = new Meteor.Collection('Events');

if (Meteor.isClient) {
// This code only runs on the client


Template.body.helpers({
    events: function() {
        var evs = Events.find({}, {fields: {'name':1}});
        return Events.find({}, {
            sort: {
                createdAt: -1
            }
        });
    }
});
}

My question essentially boils down to, how do I store a reference to my mongo collection in a variable in header.js if it gets created in Events.js? Orion doesn't have a great documentation set and meteors lacks in places too, so this is a bit opaque.

tldr: Remove the first line from your header.js file

If you look more carefully at the traceback that is telling you the Events model is already exists, you will see it is being thrown by the header.js file, line 1. That is because when this file is loaded the Events variable is already defined, as it is the name of the global variable defined in Events.js, and is already available in this current file (and everywhere that Events.js has executed).

For most projects the best practice is to define your collections globally, in a file that is executed on both the client and server. Then all your other files can refer to the collection using this variable.

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