I have a Mongoose model that holds Places. Each place has a lat/lng. I can define a Mongoose virtual attribute called distance that would be used to sort Places in ascending order. What's the best way to refer to the user's location information (let's assume it's stored in a session variable for now) from inside the distance virtual attribute?
-
I don't quite understand your question. Virtual attributes of Place should only refer to other properties of Place, not data in the session.– JohnnyHKJul 31, 2012 at 17:17
-
@JohnnyHK You're right -- I'm asking for a virtual attribute that depends on something that isn't a property of Place. Is that possible? Even if it is possible, is using a virtual attribute the best way of implementing it?– James SunJul 31, 2012 at 18:30
-
No, for anything involving external data I think you'd want to add a method to the schema instead.– JohnnyHKJul 31, 2012 at 18:50
-
@JohnnyHK Thanks for your answer. Using a method is definitely a better approach!– James SunAug 1, 2012 at 13:33
-
Glad it helped. I'll add that as an answer so we can close out the question.– JohnnyHKAug 1, 2012 at 13:40
3 Answers
For anything involving external data, adding a method to the schema would be a better choice than a virtual property.
I'm solving a similar issue. The problem is that methods are fine if you want perform an operation on a single value but I'm retrieving a list and want to inject a new virtual field into every record in the list - but use session data to generate the field. to do this safely (avoiding globals), I think I'll need to use a QueryStream and inject the new field using an ArrayFormatter that takes the session variables as constructor parameters.
This also looks like a job for LINQ so another approach might be to use one of the ports of LINQ to JS.
If you sill prefer to use virtuals, you can store user location info in NodeJs globals. For example this code may be set after user login:
global.user_location = user.location;
-
2I wonder if using globals might be a little risky given that the server may be processing multiple user requests concurrently. You may be able to get away with it but if your task is pending a callback, I suspect that a different user's location may end up in the global. Jan 1, 2013 at 8:56