universo-platform-3d
61 строка · 2.8 Кб
1import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'
2import { ApiProperty } from '@nestjs/swagger'
3import { User } from '../../user/user.schema'
4import * as mongoose from 'mongoose'
5import { Document } from 'mongoose'
6import { Space } from '../../space/space.schema'
7import { SpaceObject } from '../../space-object/space-object.schema'
8
9export class CustomDataPublicData {}
10
11export type CustomDataDocument = CustomData & Document
12
13/**
14* CustomData is a collection of arbitrary data that can be attached to any other collection via customData: ObjectId[]. This allows a user to store arbitrary data that is not part of the schema of the collection.
15*
16* As of 2023-03-02 21:25:21, there aren't any controller/service methods because CustomData should be retrieved via populate('customData') on the other collection.
17*
18* Reasons for having customData in a separate schema:
19* 1. Clean separation between custom key/value pairs from users and the data TM stores
20* 2. CustomData can be used by multiple collections and "moved" from different schemas
21* 3. CustomData optimizes storage with staying in a separate collection. Otherwise, MongoDB will dynamically expand storage allocated for the collection, which would affect performance as we grow. See this post from a MongoDB tech lead: https://www.askasya.com/post/largeembeddedarrays/
22* 4. We can add validation rules in the customData collection in the future via this schema
23* 5. We can optimize when to populate() customData in case it gets large
24* 6. We can manage indexes ourselves on CustomData
25* 7. We can add discriminators/subclasses for specific use cases, such as whitelabel clients
26* 8. By decoupling CustomData from other entities like Spaces, the same CustomData can be used by multiple Spaces (or any other entity).
27*/
28@Schema({
29timestamps: true,
30toJSON: {
31virtuals: true
32},
33minimize: false // store empty data: {} upon creation
34})
35export class CustomData {
36/**
37* @description All customData data is stored in a "data" key (customData.data). Keys of customData.data can be of type string, number, Date, or boolean. (We can add JSON in the future, as well as references to other entities). This is the simplest implementation for now.
38* @date 2023-03-03 22:30
39*/
40@Prop({
41type: () => mongoose.Schema.Types.Array,
42default: {},
43required: true
44})
45@ApiProperty()
46data: any
47
48// @Prop is not used here; a virtual is used instead (below) due to a circular reference issue
49// creator: User
50id: string
51}
52
53export const CustomDataSchema = SchemaFactory.createForClass(CustomData)
54
55// Need to use a virtual property here so we don't get a circular reference issue
56CustomDataSchema.virtual('creator', {
57ref: 'User',
58localField: 'creator',
59foreignField: '_id',
60select: '_id displayName'
61})
62