【问题标题】:how to get mongoose session in mongoose schema validator如何在猫鼬模式验证器中获取猫鼬会话
【发布时间】:2021-06-20 10:05:44
【问题描述】:

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

场景

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

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

编辑:添加示例


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

【问题讨论】:

  • 这要么是 github 问题的错误,要么是实现中的错误。你能分享你的代码来显示验证器吗?
  • 我添加了一个例子。我根本不明白“这个”应该指的是什么,以及如何。它是未定义的。

标签: mongodb mongoose mongoose-schema


【解决方案1】:

你不应该使用javascript arrow function

箭头函数表达式是传统函数表达式的紧凑替代方案,但受到限制且不能在所有情况下使用。

差异和限制:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2011-11-14
    • 1970-01-01
    • 2016-08-05
    相关资源
    最近更新 更多