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

Error is thrown on Array schema types with null value #35

Closed Sebmaster closed 3 months ago

Sebmaster commented 4 months ago

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

Bug

What is the current behavior?

mongoose queries error when processing a record which contains null as a value of an Array schema type.

TypeError: Cannot read properties of null (reading 'map')
    at /mongoose-test/node_modules/mongoose-lean-getters/index.js:130:67
    at Schema.eachPath (/mongoose-test/node_modules/mongoose/lib/schema.js:1569:5)
    at model.Query.applyGettersToDoc (/mongoose-test/node_modules/mongoose-lean-getters/index.js:110:16)
    at model.Query.applyGetters (/mongoose-test/node_modules/mongoose-lean-getters/index.js:51:25)
    at model.Query.<anonymous> (/mongoose-test/node_modules/mongoose-lean-getters/index.js:36:18)
    at next (/mongoose-test/node_modules/kareem/index.js:268:35)
    at Kareem.execPost (/mongoose-test/node_modules/kareem/index.js:296:3)
    at /mongoose-test/node_modules/mongoose/lib/query.js:4380:28
    at new Promise (<anonymous>)
    at _executePostHooks (/mongoose-test/node_modules/mongoose/lib/query.js:4377:10)

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

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

const schema = new mongoose.Schema({
  foo: { type: String },
  arr: { type: [String] },
});
schema.plugin(getters);
const Model = mongoose.model('Test', schema);

(async () => {
  await mongoose.connect('mongodb://localhost:27017/unitTest');
  const { id } = await Model.create({ foo: 'bar', arr: null });
  const m = await Model.findById(id, {}, { lean: { getters: true } });
  console.log(m.arr);
})();

What is the expected behavior?

Model should be returned without any modification.

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

Mongoose: 8.3.4 mongoose-lean-getters: 2.1.0 Node.js: v18.20.2

Sebmaster commented 4 months ago

This causes a fairly big issue: A process that encounters this condition will crash. This is due to the way mongoose-lean-getters registers its hook which doesn't catch errors that are thrown. This in turn leads to an uncaughtException when used with cursor.eachAsync.