jagi / meteor-astronomy

Model layer for Meteor

Home Page:https://atmospherejs.com/jagi/astronomy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Detect if a field was hidden in afterInit event

dnish opened this issue · comments

commented

Hey,
I'm currently adding some data in my afterInit event. It currently looks like this:

Posting.js

afterInit(e) {
  const doc = e.currentTarget;
  doc.userDoc = User.findOne({_id: doc.userId});
}

Because of some performance improvements, I want to disable the loading of the user document. I know that I can disable events via options, but there may be some other code, which still should run. So I want to create a query like this:

Posting.findOne({},{fields:{userDoc:0}});

Now the problem happens: I'm not able to get the options parameter within the afterInit event, so I'm not able to detect if I had disabled the field. After reading the documentation, I found out, that the afterFind event could help. Because it also returns the result, I could add the userDoc object if it wasn't disabled in the options. That works fine if I do a findOne(), but will fail if I do a find().fetch(), because in this case, result returns a MongoCursor instead of the result array.

So, what would be the best way to attach additional data depending on the options?

I wouldn't rather use afterInit/afterFind for this purpose. It's better to create a method that would take a boolean argument. If it's set then it will fetch and store related document in the main document.

commented

Hey,
thank you for the quick response. Adding an own method like findWithRelations was my first thought, but normally it is easier to load all relational data with the object, so other members of the team will not forgot, that they have to use this method instead of find(). There is currently just one case, where the userDoc is useless (preview function), and that's why I want to add the condition.

I'm just wondering about the afterFind event. The docs are saying, that we can modify the results in that event. But result is a MongoDB cursor and doesn't return the docs array. Is there another prop where the results are saved?

It's just a limitation of this system. Fixing it would be really hard. The userDoc is not really a part of the original object so it's bad design decision to use fields for that. You should really use method for that.