Reputation: 1333
I have this Meteor publication of all the posts in the database.
I would like to return the owner
field of the post only if the isAnonymous
field of the post is true (i.e. if the post is anonymous, don't publish the owner?
How do I make this condition in Meteor/Mongodb? The script that I've got here never returns the owner.
Meteor.publish('posts', function(id) {
var posts = Posts.find({},{fields: {owner: 0}},{sort: {created_at: -1}});
return posts;
});
I tried something like this, but it doesn't work
Meteor.publish('posts', function(id) {
var posts = Posts.find({},{fields: {owner: { $cond: [ { $eq: [ "isAnonymous", 1 ] }, 0, 1 ] }}},{sort: {created_at: -1}});
return posts;
});
Upvotes: 1
Views: 337
Reputation: 50406
What you seem to want here is something like this:
Meteor.publish('posts',function(args) {
var self = this;
Posts.find().fetch().forEach(function(post) {
if ( post.hasOwnProperty("isAnonymous") ) {
if ( post.isAnonymous ) {
delete post.owner;
delete post.isAnonymous;
}
}
self.added("postsFiltered",post._id,post);
});
self.ready();
});
Then basically define your collection within the client at least as:
Posts = new Meteor.Collection("postsFiltered");
And then after you subscribe, the client will only see the data without the "privacy" information as it is always published that way.
Upvotes: 2
Reputation: 6676
If you don't want to return a field in some cases only, you can define a transform function for your collection. Something like this:
Posts = new Mongo.Collection('posts', {
transform: function(doc) {
if (-- condition for not returning owner is true --) {
delete doc.owner;
}
}
});
If you are ok with returning it, but don't want to display it in some cases, you can do this in the template like so:
{{#each posts }}
...
{{#if isOwnerKnown owner }}
{{ owner }}
{{/if }}
...
{{/foreach}}
Template.people.helpers({
isOwnerKnown: function(owner){
return owner != 'Anonymous';
}
...
});
Upvotes: 1