Mongoose: Lean populate doesn't return virtual field

Created on 22 May 2017  路  7Comments  路  Source: Automattic/mongoose

Description
I'm trying to do combine lean & populate for returning a virtual field. However virtual field name isn't being returned.

Question Schema:

const QuestionSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
    trim: true,
  },
  question: {
    type: String,
    required: true,
    trim: true,
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
...
});

const Question = mongoose.model('Question', QuestionSchema);

User Schema:

const UserSchema = new mongoose.Schema({
  email: {
    type: String,
    unique: true,
    required: true,
    trim: true,
  },
...
});

UserSchema.virtual('name')
  .get(function () {
    if (this.nickname) {
      return this.nickname;
    } else if (this.firstName || this.lastName) {
      return `${this.firstName} ${this.lastName}`;
    } else {
      return this.email.substr(0, this.email.indexOf('@'));
    }
  });

Query (bug is here)

      .find(query)
      .lean()
      .populate('author', {email: 1, name: 1})
      .select('-fraudStatus -entityStatus -__v')
      .then((questions) => {
        if (req.user.type === Constant.user.type.journalist) {
          questions.forEach((question) => {
            question.answers = question.answers.length;
          });
        } else if (req.user.type === Constant.user.type.source) {
          questions.forEach((question) => {
            question.answers = question.answers.find((answer) => answer.author.equals(req.user._id)) ? 1 : 0;
          });
        }
        res.json(questions);
      })
      .catch((err) => {
        next(err);
      });
  }

Steps to reproduce

  1. Define schema with virtual field name
  2. Do a query with lean & populate virtual field name
  3. Check result contain email but not name field

Expected
name should be returned

Actual
name not returned response

enhancement

Most helpful comment

Should be fixed with 4.11 plus https://github.com/vkarpov15/mongoose-lean-virtuals .

All 7 comments

I think this is duplicate #5232 . Please confirm

No, these 2 issues are independent. Using lean() turns off virtuals by design, so lean() means no virtual populate currently. Will add the ability to turn virtuals on with lean() in a future release, this has come up a few times in various contexts.

Should be fixed with 4.11 plus https://github.com/vkarpov15/mongoose-lean-virtuals .

When will this be released? :)

Planning on releasing 4.11 this week, here's the milestone: https://github.com/Automattic/mongoose/milestone/162 . Work is done, just waiting on some more reviews and final testing.

How can i turn virtuals on with lean() in mongoose v4.11.1?

@shreyawhiz use the https://www.npmjs.com/package/mongoose-lean-virtuals plugin. I had forgotten to publish it on npm, but it's up now.

Was this page helpful?
0 / 5 - 0 ratings