如何在猫鼬模式验证器中获取猫鼬会话
how to get mongoose session in mongoose schema validator
我想验证模式中的引用,我需要验证器才能访问会话。
场景
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
你不应该使用 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.
将其更改为常规函数声明应该可以修复它:
validate: async function (val){
console.log("this", this);
}
我想验证模式中的引用,我需要验证器才能访问会话。
场景
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
你不应该使用 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.
将其更改为常规函数声明应该可以修复它:
validate: async function (val){
console.log("this", this);
}