Как проверить, является ли документ подсхемой mongoose в промежуточном программном обеспечении?Javascript

Форум по Javascript
Ответить
Anonymous
 Как проверить, является ли документ подсхемой mongoose в промежуточном программном обеспечении?

Сообщение Anonymous »

Я создаю мультитенантное приложение и использую глобальный плагин вместо добавления плагина к каждой модели по одному. Этот плагин будет обрабатывать добавление идентификатора организации во время фильтров, сохранения и агрегирования.
Но проблема в том, что он добавляет идентификатор организации во вложенные документы. Я просто хочу добавить идентификатор организации на верхний уровень.

Код: Выделить всё

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]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»