I am in the process of setting up a MERN project in Typescript and I have come across something that puzzles me. Despite my expectations, there is no compilation error in TS with the following code:
Here's the model snippet:
import { Document, Schema, model } from "mongoose";
export interface Hello extends Document {
name: string;
}
const helloSchema = new Schema({
name: {
required: true,
type: String,
},
});
const helloModel = model<Hello>("Hello", helloSchema);
export default helloModel;
and it is used as follows:
import express from "express";
import helloModel from "./model";
const app = express();
app.get("/", (req, res) => {
res.send("hi");
});
const x = new helloModel({ age: 1 }); <===== no errors here
app.listen(7000);
I expected to see compilation errors indicating that x does not match the defined interface. Could it be that I am using the model incorrectly? Being new to MongoDB and Typescript, I might be missing something obvious.
Thank you to anyone who can offer an explanation.
EDIT FOLLOW-UP I discovered this information in the @types files:
/**
* Model constructor
* Provides the interface to MongoDB collections as well as creates document instances.
* @param doc values with which to create the document
* @event error If listening to this event, it is emitted when a document
* was saved without passing a callback and an error occurred. If not
* listening, the event bubbles to the connection used to create this Model.
* @event index Emitted after Model#ensureIndexes completes. If an error
* occurred it is passed with the event.
* @event index-single-start Emitted when an individual index starts within
* Model#ensureIndexes. The fields and options being used to build the index
* are also passed with the event.
* @event index-single-done Emitted when an individual index finishes within
* Model#ensureIndexes. If an error occurred it is passed with the event.
* The fields, options, and index name are also passed.
*/
new (doc?: any): T;
It appears that the inclusion of doc?: any explains why there is no compile error. Does this mean that in general, when combining Mongo schemas with TS interfaces, we can only enforce type checking on Read, Update, and Delete operations rather than Create?