0

I have defined Getters in UserSchema, getters are getting called when querying the User Model, But when querying through the populate method the getters are not being called. How can we invoke getters in such an instance? Please find below the query and schema.

Query:

Post.findById(req.query.postId, '-updated_at -created_at')
.populate('_user userInvited._user','_id username photo')
.exec(function (err, post) { // Handle Actions });

User Schema

// user schema
var UserSchema = new Schema({
name: String,
username: String,
photo: {type: String, get: imagePath, default: ''},
}, {timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}});

// Getters
function imagePath(photo) {

     var image = (photo && photo != "") ? photo : App.imageUrl('user.jpg');
     return image;
}

Post Schema

// Define User Schema
var userSchema = [{type: Schema.Types.ObjectId,ref: 'User'}];

// Define Post Schema
var PostSchema = new Schema({
_user: {type: Schema.Types.ObjectId,ref: 'User',required: true},
text: {
    type: String,
    required: true
},
userInvited: userSchema,
}, {timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}});
Binu Vijayan
  • 56
  • 1
  • 5
  • Maybe related: [Why are my Mongoose 3.8.7 schema getters and setters being ignored?](https://stackoverflow.com/questions/21832088/why-are-my-mongoose-3-8-7-schema-getters-and-setters-being-ignored) – Mikey Aug 19 '17 at 13:09
  • Yes Mikey, Thanks a lot. following solution worked https://stackoverflow.com/a/24458856/2218578 – Binu Vijayan Aug 19 '17 at 13:24

0 Answers0