mongoosejs / mongoose-lean-getters

Apply getters on lean() documents: https://mongoosejs.com/docs/tutorials/lean.html
Apache License 2.0
10 stars 15 forks source link

Bug: empty fields showing as undefined #20

Closed dantenol closed 1 year ago

dantenol commented 1 year ago

Do you want to request a feature or report a bug? Bug What is the current behavior? The package shows all missing fields as undefined after a lean find with getters: true.

If the current behavior is a bug, please provide the steps to reproduce. Minimal example:

const User = new Schema({
   firstName: {
      type: String
      get: capitalize()
    },
    email: {
       type: String,
     }
})

And performing a lean 'find' it includes undefined

User.create({ firstName: 'name' })

User.findOne().lean({ getters: true }) // { firstName: 'Name', email: undefined }
User.findOne().lean() // { firstName: 'name' }

What is the expected behavior?

User.create({ firstName: 'name' })

User.findOne().lean({ getters: true }) // { firstName: 'Name' }

What are the versions of Node.js, mongoose-lean-getters, and Mongoose are you are using? Note that "latest" is not a version.

Node version18.12 Mongoose version 6.8.0 mongoose-lean-getters version 0.3.5

IslandRhythms commented 1 year ago

I'm getting a couple bugs trying to reproduce this issue, but am still able to reproduce.

  1. the parameter passed to the capitalize function is undefined which is why I had to comment out the process.
  2. not adding getters: true to the second findOne() call returns no properties other than version and id.
const mongoose = require('mongoose');

const mongooseLeanGetters = require('mongoose-lean-getters');

const testSchema = new mongoose.Schema({
  firstName: {
    type: String,
    get: capitalize
  },
  email: String
});

function capitalize(firstName) {
  /*
  console.log('what is firstName', firstName);
  let Capitalize = firstName.charAt(0).toUpperCase() + firstName.slice(1);
  return Capitalize;
  */
  return 'Test';
}

testSchema.plugin(mongooseLeanGetters);

const Test = mongoose.model('Test', testSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await mongoose.connection.dropDatabase();

  await Test.create({
    name: 'test'
  });

  const res = await Test.findOne().lean({ getters: true });
  const otherRes = await Test.findOne().lean();
  console.log(res);
  console.log('========================');
  console.log(otherRes);
}

run();

Output:

{
  _id: new ObjectId("63b46f05cf9c38eb316a7812"),
  __v: 0,
  firstName: 'Test',
  email: undefined
}
========================
{ _id: new ObjectId("63b46f05cf9c38eb316a7812"), __v: 0 }
IslandRhythms commented 1 year ago

Just realized the doc I create has the wrong key name

vkarpov15 commented 1 year ago

Fixed by #21