mongoosejs / mongoose-lean-virtuals

Attach virtuals to the results of mongoose lean() queries
Apache License 2.0
45 stars 24 forks source link

Virtuals called on null sub-document field #63

Closed Sagie501 closed 1 year ago

Sagie501 commented 2 years ago

Do you want to request a feature or report a bug? Bug

What is the current behavior? If a sub-document is null and there is a virtual on it the sub-document is initialized as an object with the virtual instead of stay null

If the current behavior is a bug, please provide the steps to reproduce. Consider the following setup:

import mongoose from "mongoose";
import { mongooseLeanVirtuals } from "mongoose-lean-virtuals";

mongoose.plugin(mongooseLeanVirtuals);

const ChildSchema = new mongoose.Schema({
  age: { type: Number }
}, { _id: false })

const UserSchema = new mongoose.Schema({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  child: { type: ChildSchema }
});

UserSchema.virtual('child.parentName').get(function () {
  return `${this.firstName} ${this.lastName}`;
});

const UserModel = mongoose.model('users', UserSchema);

run().catch(console.error);

And the following run function:

async function run() {
  await mongoose.connect('');

  await UserModel.create({
    firstName: 'Homer',
    lastName: 'Simpson'
  });

  const result: any = await UserModel.findOne({}).lean({ virtuals: true }).exec();

  assert.equal(result.firstName, 'Homer'); // Pass
  assert.equal(result.lastName, 'Simpson'); // Pass
  assert.equal(result.child, null); // Fail

  console.log(result);
}

As you can see I expect that child field will be null but actually the value is: { parentName: 'Homer Simpson' }. If I tweak the create a bit like that:

  await UserModel.create({
    firstName: 'Homer',
    lastName: 'Simpson',
    child: null
  });

Then I get a runtime error Cannot read properties of null which is even worst.

What is the expected behavior? I expect that if a field is null then no virtual should run on it.

What are the versions of Node.js, mongoose-lean-getters, and Mongoose are you are using? Note that "latest" is not a version. Package Version
mongoose 6.5.0
mongoose-lean-getters N/A
mongoose-lean-virtuals 0.9.1
Node.js 16.13.0