如何在猫鼬模式验证器中获取猫鼬会话

时间:2021-03-23 17:40:01

标签: mongodb mongoose mongoose-schema

我想验证架构中的引用,我需要验证器才能访问会话。

场景

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

需要

我想验证引用的对象是否存在,但要做到这一点,我需要访问验证器内部的会话。

这个 github 问题看起来很相似,但是 this.$session() 对我不起作用 https://github.com/Automattic/mongoose/issues/7652

我只是不明白“这个”应该指的是什么。

编辑:添加示例


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();

和输出:

this undefined

1 个答案:

答案 0 :(得分:0)

您不应该使用 javascript arrow function

<块引用>

箭头函数表达式是传统函数表达式的紧凑替代品,但有局限性,不能在所有情况下使用。

差异和限制:

  • 没有自己的 this 或 super 绑定,不应用作方法。

将其更改为常规函数声明应该可以修复它:

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