Hacer referencia a datos basados ​​en sesiones en un atributo virtual Mongoose

I have a Mongoose model that holds Places. Each place has a lat/lng. I can define a Mongoose atributo virtual , que son distancia 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 distancia virtual attribute?

preguntado el 31 de julio de 12 a las 11:07

I don't quite understand your question. Virtual attributes of Place should only refer to other properties of Place, not data in the session. -

@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? -

No, for anything involving external data I think you'd want to add a Método to the schema instead. -

@JohnnyHK Thanks for your answer. Using a method is definitely a better approach! -

Glad it helped. I'll add that as an answer so we can close out the question. -

3 Respuestas

For anything involving external data, adding a Método to the schema would be a better choice than a virtual property.

Respondido 01 ago 12, 14:08

but how do you call the method on a collection? - Chovy

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 de manera segura (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.

Respondido el 01 de enero de 13 a las 09:01

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;

respondido 19 nov., 12:11

I 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. - Tony O'Hagan

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.