Add a new field to the Typegoose subdocument #726
-
How do I include an extra field in the User class subdocument? Inside the user's cars subdocument, I need a field that indicates the active or deactivated car for that user. class Car {
@prop()
public model?: string;
}
class User {
@prop()
public name?: string;
@prop({ required: true })
public age!: number;
@prop({ ref: () => Car })
public cars?: Ref<Car>[];
} Populated Car Collection: Car A
{
"_id": "1"
"model": "Ferrari"
}
Car B
{
"_id": "2"
"model": "Tesla"
} User collection populated according to the default class: User
{
"_id": "1",
"name": "Jonh Doe",
"age": 25,
"cars": [
{ "_id": "1" },
{ "_id": "2" }
]
} I need to include a "status" field in the cars array of the User collection, as shown below: status is to identify whether the car model is active for the user User
{
"_id": "1",
"name": "Jonh Doe",
"age": 25,
"cars": [
{ "_id": "1", "status": false },
{ "_id": "2", "status": true }
]
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You have multiple options:
Example 1: class Car {
@prop()
public model?: string;
}
class UserCarSub {
@prop({ ref: () => Car })
public car: Ref<Car>;
@prop()
public extra_properties: string;
}
class User {
@prop()
public name?: string;
@prop({ required: true })
public age!: number;
@prop()
public cars?: UserCarSub[];
} Example 2: // the first example does not use virtual populate
class Car {
@prop()
public model?: string;
}
class UserCarProperties {
@prop({ ref: () => Car })
public car: Ref<Car>;
@prop({ ref: () => User })
public user: Ref<User>;
@prop()
public extra_properties: string;
}
class User {
@prop()
public name?: string;
@prop({ required: true })
public age!: number;
@prop({ ref: () => Car })
public cars?: Ref<Car>[];
@prop({ ref: () => UserCarProperties })
public car_properties: Ref<UserCarProperties>[];
}
// the following uses virtual populate
class User {
@prop()
public name?: string;
@prop({ required: true })
public age!: number;
@prop({ ref: () => Car })
public cars?: Ref<Car>[];
@prop({ ref: () => UserCarProperties, foreignField: 'user', localField: '_id' })
public car_properties: Ref<UserCarProperties>[]; // this property does not exist in the database, but can still populate
} Alternatively you could also in Example 2 merge the cars references into the Personally i would suggest Example 2 with virtual populate (merged) if the array is of unknown length or could grow to unknown length Edit: i have also found this issue on stackoverflow, in case anyone comes across here |
Beta Was this translation helpful? Give feedback.
You have multiple options:
status
property on the car itselfExample 1: