gpt4 book ai didi

typescript - 如何访问 typescript/mongoose 中填充文档的字段?

转载 作者:行者123 更新时间:2023-12-05 05:29:43 26 4
gpt4 key购买 nike

我正在填充 Customer 模型并使用助手类对其进行转换。但我无法访问填充字段的子字段。

订单模型

const orderSchema = new Schema<IOrder>({
customerID: {
type: Schema.Types.ObjectId,
ref: "Customer",
required: true,
}
}

export const OrderModel = model<IOrder, IOrderModel>("Order", orderSchema);

订单接口(interface)

export interface IOrder{
_id?: Schema.Types.ObjectId;
customerID: Schema.Types.ObjectId;
}

export interface IOrderModel extends Model<IOrder> {
}

订单助手

export class OrderHelper {
private customer: Schema.Types.ObjectId;

constructor(model: IOrder) {
this.customer = model.customerID;
}
}

订单服务

class OrderService {
private readonly orderRepository: OrderRepository;

constructor() {
this.orderRepository = new OrderRepository();
}

public async getProducts(request: Request) {
const products = await this.orderRepository.findOrders(request.body);
const data: ProductsHelper[] = [];
for (let key in products) data.push(new ProductsHelper(products[key]));
return data;
}
}

订单存储库


export class OrderRepository {
constructor() {
}

public async findOrders(body: Partial<IOrder>) {
const orders = await OrderModel.find(body)
.populate({
path: "customerID",
select: ["customerCode", "citizenship", "passportSerial"],
}).lean();
return orders;
}
}

例如,我想访问 Customer 的 customerCode 字段。但它给我 TypeError 没有 customerCode 字段。我怎么解决这个问题?它与接口(interface)/类型或其他什么有关吗?

最佳答案

您应该在订单接口(interface)和助手中声明客户的类型。然后您将能够访问它的(给定接口(interface)的)字段。

关于typescript - 如何访问 typescript/mongoose 中填充文档的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74863962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com