Search code examples
mongodbmongoosemongoose-schema

how to get mongoose session in mongoose schema validator


I want to validate a reference in a schema, and I need the validator to be able to access the session.

Scenario

start mongoose session
start mongoose transaction
insert entry to a table
insert entry to another table, with a reference to the first entry

Desired

I want to validate the referenced object exists, but to do that, I need access to the session, inside the validator.

this github issue seems similar, but this.$session() isn't working for me https://github.com/Automattic/mongoose/issues/7652

I simply don't understand what "this" is supposed to be referring to.

EDIT: adding example


import mongoose from "mongoose";

async function run() {
  // User data root schema
  const userSchema = new mongoose.Schema(
    // Define the data schema
    {
      accountId: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        validate: async (val) => {
          console.log("this", this);
        }
      }
    }
  );

  const User = mongoose.model("User", userSchema);

  const url = null; // secret
  const options = {};
  await mongoose.connect(url, options);

  const user = new User({ accountId: "605c662ba2cde486ecd36a4a" });
  await user.save();
}

run();

And the output:

this undefined

Solution

  • You shouldn't use a javascript arrow function

    An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.

    Differences & Limitations:

    • Does not have its own bindings to this or super, and should not be used as methods.

    Changing it to regular function declaration should fix it:

        validate: async function (val){
          console.log("this", this);
        }