【发布时间】: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