【发布时间】:2021-12-19 17:04:31
【问题描述】:
我正在使用 NestJs (TypeScript) 和 mongoose 来持久化到 mongodb,我有一个这样的界面(在一个文件中):
import * as mg from 'mongoose' ;
export const ProductSchema = new mg.Schema(
{
title: { type : String, required: true},
description: { type : String, required: true},
price: { type: Number, required: true}
}
)
export interface Product{
title: string ;
description: string ;
price: number ;
}
然后使用模型的另一个类,像这样:
@Injectable()
export class ProductsService {
private products: Product[] = [];
constructor(
@InjectModel('Product') private readonly productModel: Model<Product>
) { };
async findProduct(prodId: string) {
const product = await this.productModel.findById(prodId)
if (!product) {
console.log("product null")
throw new NotFoundException('no product with that id');
}
return { id: product.id, title: product.title, description: product.description, price: product.price };
}
}
令人惊讶的是,在最后一个函数findProduct() 中,当我执行product.id(最后一行)时没有错误,并且代码可以神奇地运行。显然,我的Product模型中没有id字段,当然在mongodb中,id字段是_id(id前的下划线)。
为什么代码有效?
【问题讨论】:
标签: typescript mongodb mongoose nestjs