简体   繁体   中英

meteor.js - where to call a lookup to a collection

So I have two collections, 'Posts' and 'Locations' and a simple html form for users to add themselves into the Posts collection. Once added, I display a list of all users but also want to add some extra data to this list if they have attributes which appear in the Locations collection.

So, as an example, the user form has Name, Age, Location and the Locations collection has information on the location they live in, such as "London, Capital, UK". If a user from London enters their details I'd like to display the details they entered on the form along with "You live in a Capital city" if their location features in the Locations collection.

So, some code to insert the details from the form:

post_submit.js:

Template.postSubmit.events({
  'submit form': function(e) {
    e.preventDefault();

    var post = {
      name: $(e.target).find('[id=usersName]').val().toUpperCase();,
      age: $(e.target).find('[id=age]').val(),
      location: $(e.target).find('[id=location]').val().toUpperCase(),
    };

    Meteor.call('postInsert', post, function(error, result) {
      // display the error to the user and abort
      if (error)
        return throwError(error.reason);

      Router.go('postPage', {_id: result._id});  
    });
  }
});

and in posts.js

Meteor.methods({
  postInsert: function(postAttributes) {

    var post = _.extend(postAttributes, { 
      submitted: new Date(),
    });

    var postId = Posts.insert(post);

    return {
      _id: postId
    };
  }
});

But how do I define the subscription to the Locations collection and where do I call the 'lookup' to that collection in order to lookup the location and then enable me to display that in some other portion of the page. I'm sure this is pretty simple, I'm struggling to connect the dots though.

You'll have to make a new publication that publishes the Posts and then publishes the Locations as a "dependency". There is a package that makes this very simple. copleykj:simple-publish will help you accomplish this. The samples in the readme should be enough to get you started.

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