Search code examples
node.jsmongoosemongoose-populate

Exclude virtual fields


I have a virtual field fullname:

UserSchema.virtual('fullname').get(function() {  
  return this.firstName + ' ' + this.lastName;
});

Sometimes I want this field in my query result and sometimes I don't. I haven't figured out how to exclude it. This is what I have tried (didn't change anything):

UserModel.findOne({ '_id': userId })
  .select('-fullname')
  .exec(callback);

Should I approach this in some other way?


Solution

  • Try to disable virtuals in toJSON and in toObject and include them in the query you want them

    UserModel.findOne({ _id: userId })
       .then(doc => console.log(doc.toObject({ virtuals: true }));
    

    If you want to exclude specific fields you can just delete them before sending the doc.

    UserModel.findOne({ _id: userId })
       .then(doc => doc.toObject({ virtuals: true }))
       .then(doc => {
         delete doc.mySecretVirtual;
         return doc;
       });