将新字段添加到TypeGoose子登记
我如何在用户类的子记录中包含一个额外的字段?
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>[];
}
填充的汽车集合:
Car A
{
"_id": "1"
"model": "Ferrari"
}
Car B
{
"_id": "2"
"model": "Tesla"
}
根据默认类填充的用户集合:
User
{
"_id": "1",
"name": "Jonh Doe",
"age": 25,
"cars": [
{ "_id": "1" },
{ "_id": "2" }
]
}
我需要在用户集合的汽车阵列中包含一个“状态”字段,如下所示:
- 状态是确定汽车模型是否为用户使用
User
{
"_id": "1",
"name": "Jonh Doe",
"age": 25,
"cars": [
{ "_id": "1", "status": false },
{ "_id": "2", "status": true }
]
}
How do I include an extra field in the User class subdocument?
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 }
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Hasezoey帮助我解决了GitHub问题。
这是链接和他的回答。
https://github.com/typegoose/typegoose/typegoose/typegoose/discussions/discussions/726
选项:
将当前参考数组作为子数字纪录片(请参阅示例1)
包括汽车本身的状态属性
有一个单独的类,该类在用户卡引用上具有唯一的化合物索引,并且具有您想要的属性,并且在用户中具有这样的参考字段(无论是通过虚拟填充或具有明确的参考阵列)(请参阅示例2)
示例1 1 :
示例2:
poftual
virtual 示例2将汽车的引用合并到UserCarproperties中并使用它来找到汽车,这完全取决于您
个人想要的方式,如果阵列的长度不知道或可能长到未知的长度,则建议使用Virtual Puthulate(合并)示例2
Hasezoey helped me with the github issue.
Here's the link and his answer.
https://github.com/typegoose/typegoose/discussions/726
You have multiple options:
make the current reference array a subdocumentarray (see example 1)
include the status property on the car itself
have a separate class that has a unique compound index on the user-car references and has the properties you want and have such a reference field in the user (either through virtual populate or with a explicit ref array) (see example 2)
Example 1:
Example 2:
Virtual Populate
Alternatively you could also in Example 2 merge the cars references into the UserCarProperties and use that to find cars, that is fully up to how you want it
Personally i would suggest Example 2 with virtual populate (merged) if the array is of unknown length or could grow to unknown length