zangetsu
zangetsu

Reputation: 127

Add an extra field to collection only on the client side and not affecting server side

Is there a way to add or inject an additional or new field to a collection and then being able to access that newly inserted field to the collection on the client side and displaying it on a template or accessing it without affecting the server side? I didn't want to compromise with the APIs or the database since it's simply a count of something, like when a customer has a total of 8 deliveries.

I was doing this code where I'm subscribing to a collection and then trying to update the collection on the client side but obviously I should have no rights on updating it:

Meteor.subscribe("all_customers", function () {
    Customer.find({}).forEach(function(data) {
        var delivery_count = Delivery.find({ customerID: data._id }).count();
        Customer.update( { _id: data._id } , { $push: { deliveries: delivery_count } } );
    });
}),

And then doing this one where I'd try to manipulate the collection by inserting new key-value pair but it won't display or nothing at all when it's sent:

Meteor.subscribe("all_customers", function () {
    Customer.find({}).forEach(function(data) {
        var delivery_count = Delivery.find({ customerID: data._id }).count();
        data.deliveries = delivery_count;
    });
}),

My main objective is to basically be able to sort the count of the deliveries in the EasySearch package without compromising with the APIs or database but the package only sorts an existing field. Or is there a way to do this with the package alone?

Forgive me if this question may sound dumb but I hope someone could help.

Upvotes: 0

Views: 46

Answers (1)

ko0stik
ko0stik

Reputation: 658

It's completely possible, for that you can use low level publications described here: https://docs.meteor.com/api/pubsub.html

You have 2 solutions, one standard, the other hacky:

  • You follow documentation, you transform your document before sending it to the client. Your server data is not affected and you can enhance data (even do joins) from your subscription. It's cool but you can't push it too far as it might collide and conflict with another publication for the same collection on the same page. Solution is well explained here: How to publish a view/transform of a collection in Meteor?
  • You can do a client-only collection which will be customs objects with only the data you need. You still have a server-side observer on the source collection but you'll fetch new objects that client will treat and display without any calculation. You need more code but this way, you don't mess with classic server-client collections. It's a bit overkill so ping me if you want a detailed example.

Upvotes: 0

Related Questions