我想验证模式中的引用,我需要验证器能够访问会话。
场景
start mongoose session
start mongoose transaction
insert entry to a table
insert entry to another table, with a reference to the first entry
所需
我想验证引用的对象是否存在,但要做到这一点,我需要访问验证器内部的会话。
这个github问题看起来很相似,但是这个$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箭头函数
箭头函数表达式是传统函数表达式的紧凑替代方案,但受到限制,不能在所有情况下使用。
差异&限制:
- 没有自己到this或super的绑定,不应用作方法
将其更改为常规函数声明应该可以修复它:
validate: async function (val){
console.log("this", this);
}