I'm using NestJs (TypeScript) and mongoose to persist to mongodb, I have an interface like this (in one file):
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 ;
}
Then another class using the model, like this:
@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 };
}
}
Surprisingly in the last function, findProduct(), there's no error when I do product.id (last line), and the code just works magically. Obviously, there's no field id in my Product model, and of course in mongodb, the id field is _id (an underscore before id).
Why does the code work?