问题
Note: Whole code can be found here:
https://github.com/Julian-Th/crowducate-platform/
Currently, all items from an array are displayed in one single list instead of a separate list tag:
I have a pub function, which works perfectly:
Meteor.publish('editableCourses', function () {
return Courses.find({"canEditCourse": { $in: [ this.userId ] } });
});
However, I want to use the username instead. So I tried the following with no result:
Meteor.publish('editableCourses', function () {
return Courses.find({"canEditCourse": { $in: [ this.user.username ] } });
});
My JSON:
{
"_id" : "P5JFAfrxaNpApvZWW",
"createdAt" : ISODate("2015-12-30T17:38:47.506Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$lLskLjO6W2eoA06Ws5sC/upq6Stbh1eTbgTAN3wa39RCD8x7GU1ZS"
},
"resume" : {
"loginTokens" : [
{
"when" : ISODate("2015-12-30T17:38:47.605Z"),
"hashedToken" : "g2rye+mwrNNsjL3mHtxT+sYXgj3OGoEZsGRMyVEI47I="
}
]
}
},
"username" : "User1",
"emails" : [
{
"address" : "user1@test.com",
"verified" : false
}
]
}
Thanks for your help, appreciated.
回答1:
Items of the Courses Collection is what you are publishing.
So when you query with Courses.find({"canEditCourse": { $in: [ this.userId ] } }); the canEditCourse field is what you are trying to match to a userId (it literally means find all Courses where the canEditCourse array contains the userId.)
I don't see why you would want to use username here instead though. What does that get you?
If you do want to do this, then you need to have the canEditCourse field be an array of username and not userId.
That means you need to change the logic where the Courses are created or edited and where this field is being filled.
Not sure it is worth the trouble. If what you want is look Courses up by username, then look up the User by username, get his/her userId and lookup the Courses by userId.
Meteor.publish('editableCourses', function (username) {
var myUser = Meteor.users.findOne({'username': username});
return Courses.find({"canEditCourse": { $in: [ myUser._id ] } });
});
来源:https://stackoverflow.com/questions/34534557/meteor-how-to-write-a-publish-function-containing-the-username