问题
I am trying to make profile page and, I need to display the profilename and bio to a template. The problem is I can't get the Id of each profile object. If I can get the Id of each profile like how it's done in the book with postId. Here The code below is the way I thought it would work but did not. If you tell me how to get the Id that would be great thanks.
Profile = new Meteor.Collection('profile');
Profile.allow({
update: ownsDocument
})
Profile.deny({
update: function(profileId, profile, fieldNames) {
return (_.without(fieldNames, 'bio').length > 0);
}
});
Accounts.onCreateUser(function(options, user){
Meteor.methods({
profile: function(postAttributes) {
var user = Meteor.user();
var profile = _.extend(_.pick(options.profile, 'bio'), {
userId: user._id,
profilename: user.username,
submitted: new Date().getTime(),
postsCount: 0, posts : []
});
var profileId = Profile.insert(profile);
return profileId;
}
});
return user;
});
回答1:
You seem a little confused on some Meteor ideas.
Firstly Meteor.methods({ ... }) are functions that can be called client side using Meteor.call({ })
They should appear at the top level and not inside other functions like Accounts.onCreateUser
For this use case I don't see why you need a method at all though. All you want to do is retrieve data that you will be storing in data that is going to be sent to the client anyway.
If you use the accounts-base package then you automatically get a Meteor.users collection that would be fine for what you want to do. I don't see the need for a Profile collection
Here's a meteorpad illustrating it: http://meteorpad.com/pad/xL9C8eMpcwGs553YD
Note I store the bio in the profile section of the user. This is because a user can edit their own profile section by default and so I can do Meteor.users.update( ... ) client side.
This is just an example to show some of the concepts. It does have bad practice in it. For a start I would recommend adding the package accounts-ui and using the {{> loginButtons}} helper. It gives you the error checking and so on. The reason I didn't use it was because I wanted to show how to allow a user to enter their bio prior to creating the account and how you can use that in Accounts.onCreateUser.
回答2:
In the discover meteor example, they are using a method to insert a Post
and then return its id. In your case, a new Profile
is being inserted inside of an asynchronous callback so there's no way for you to return the id. However, you know the userId
, so you can use that to get the profile.
Server
Accounts.onCreateUser(function(options, user){
var user = Meteor.user();
var profile = _.extend(_.pick(options.profile, 'bio'), {
userId: user._id,
profilename: user.username,
submitted: new Date().getTime(),
postsCount: 0,
posts : []
});
Profile.insert(profile);
return user;
});
Client
Template.profile.profile = function () {
return Profiles.findOne({userId: Meteor.userId()});
};
来源:https://stackoverflow.com/questions/25215609/how-do-i-display-this-collection