How to print the full stacktrace for mongoose validation errors

Viewed 151

Is there a way to have the stacktrace show the line in code which called save?

I was testing my validation logic and noticed that Mongoose doesn't print a stacktrace to where I call save(). While the validation does say what went wrong, it is not saying where this is located.

const mySchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
  },
  accessToken: {
    type: String,
    required: true,
  },
})

mySchema.statics.createOrUpdate = async function(name, accessToken) {
  const animal = await this.findOne({ name })
  if (!animal) {
    animal = new Animal({ name }) // accessToken is missing and required
  }
  await animal.save() // expected stacktrace error here
}
  ValidationError: Animal validation failed: accessToken: Path `accessToken` is required.
      at model.Document.invalidate (/Users/michael/repos/MyApp/node_modules/mongoose/lib/document.js:2622:32)
      at /Users/michael/repos/MyApp/node_modules/mongoose/lib/document.js:2442:17
      at /Users/michael/repos/MyApp/node_modules/mongoose/lib/schematype.js:1225:9
      at processTicksAndRejections (internal/process/task_queues.js:79:11)

If I rethrow the error, I can get a more descriptive stacktrace. But I rather not need to do this:

...
await animal.save().catch((e) => { throw Error(e) })
  Error: ValidationError: accessToken: Path `accessToken` is required.
      at /Users/michael/repos/MyApp/models/Animal.js:19:42
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
0 Answers
Related