I use typescript and mongoose But mongoose can't detect invalid keys and change all typescript keys to partial
model.ts
type Coin = {
symbol: string;
name: string;
}
interface IDocument extends Coin {}
const Schema: mongoose.Schema<IDocument> = new mongoose.Schema({
symbol: String,
noItem: Number,
});
2 problems:
1- why symbol and name changed to partial key/value?
2- why mongoose cant detect wrong key? noItem
In your Mongoose Schema definition, you've defined only the symbol field from the Coin type, but name is not included. As a result, TypeScript infers the type of your Mongoose document as Partial, meaning all properties from coin are optional. To fix this, ensure that your Mongoose Schema includes all properties from your Coin type. Remember that typescript types are only present at compile time and not run time, so you need to explicitly define every item in your schema anyway, to give runtime validation.
Mongoose doesn't throw an error when you define a field in your schema that doesn't exist in your TypeScript interface. This is because Mongoose schemas are very flexible and allow you to define properties that are not strictly enforced by TypeScript types. The schema is the source of truth.
You are defining a schema here, so explicitly defining every property is good in my opinion. When you want to add an item to the model using the schema, just make sure you create it with the type IDocument or coin, this way you will get ts errors for absent/invalid properties. You could also set some default values, required properties in the schema etc, and create a third type such as CreateCoinDto.