I defined:
var PersonSchema = new Schema({
avatar: Number
});
PersonSchema.virtual("avatarUrl").get(function() {
return "http://example.com/avatar/" + this.avatar;
});
and this works in node's code likes:
PersonModel.findOne(function(err, person) {
console.log(person.avatarUrl); // http://example.com/avatar/1
});
but in jade template, if I use:
img(src!= person.avatarUrl)
this would not give what I expect.
Is there any way to make mongoose virtual works in jade?
EDIT
I think the problem is not thing to do with jade,
coz I save the "person" object in session, before I save it to session, everything on "virtual" works fine, but not works when I get it from session again.
may be it's something about the session mechanism.
not sure what 'session mechanism' you are using but if its something like connect-redis then its calling JSON.stringify(req.session)
before storing. this transforms a mongoose document into a static javascript object with no getters/setters/virtuals or other dynamic abilities. if you want the current values of your virtuals stored in the session as static values as well, you might want to call req.session.person = doc.toJSON({ virtuals: true })
.
another option is to reify the session person into a MongooseDocument after it is returned from the session.
// assume the session has been retrieved already
var person = new Person;
person.init(req.session.person);
req.session.person = person;
console.log(req.session.person.someVirtual); // yay!