Но проблема в том, что он добавляет идентификатор организации во вложенные документы. Я просто хочу добавить идентификатор организации на верхний уровень.
Код: Выделить всё
import { requestContext } from "@/utils/requestContext";
import { Schema } from "mongoose";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const organizationPlugin = (schema: any) =\> {
const hasOrgSpecificFields =
schema.path("industry") && schema.path("slogan") && schema.path("logo");
if (hasOrgSpecificFields) return;
if (schema.path("organizationId")) return;
schema.add({
organizationId: {
type: Schema.Types.ObjectId,
ref: "Organization",
index: true,
required: true,
immutable: true,
},
});
schema.pre(
/^find|count|exists|update|delete|replace/,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function (this: any) {
const store = requestContext.getStore();
if (!store?.organizationId) return;
if (this.getOptions()?.skipOrg) return;
this.where({ organizationId: store?.organizationId });
},
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
schema.pre("aggregate", function (this: any) {
const store = requestContext.getStore();
if (!store?.organizationId) return;
if (this.options?.skipOrg) return;
this.pipeline().unshift({
$match: { organizationId: store.organizationId },
});
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const setOrganizationId = (doc: any) =\> {
const store = requestContext.getStore();
if (!store?.organizationId && !doc.organizationId) {
throw new Error("Organization Id is required");
}
if (!doc.organizationId && store?.organizationId) {
doc.organizationId = store.organizationId;
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
schema.pre("save", function (this: any) {
console.log(this); //
Подробнее здесь: [url]https://stackoverflow.com/questions/79865987/how-to-check-if-a-document-is-mongoose-sub-schema-in-middleware[/url]
Мобильная версия