如何在猫鼬模式验证器中获取猫鼬会话 [英] how to get mongoose session in mongoose schema validator

查看:46
本文介绍了如何在猫鼬模式验证器中获取猫鼬会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

场景

开始猫鼬会话开始猫鼬事务向表中插入条目将条目插入另一个表,并引用第一个条目

需要

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

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

我只是不明白什么是这个"应该是指.

添加示例

<预><代码>从猫鼬"进口猫鼬;异步函数运行(){//用户数据根模式const userSchema = new mongoose.Schema(//定义数据模式{帐户ID: {类型:mongoose.Schema.Types.ObjectId,要求:真实,验证:异步(val)=>{控制台日志(这个",这个);}}});const User = mongoose.model("User", userSchema);const url = null;//秘密常量选项 = {};等待 mongoose.connect(url, options);const user = new User({ accountId: "605c662ba2cde486ecd36a4a" });等待 user.save();}跑步();

和输出:

这个未定义

解决方案

你不应该使用 javascript 箭头函数

<块引用>

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

不同之处限制:

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

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

 验证:异步函数 (val){控制台日志(这个",这个);}

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

解决方案

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

这篇关于如何在猫鼬模式验证器中获取猫鼬会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆