Trying to implement a Mongoose model in Typescript. Scouring the Google has revealed only a hybrid approach (combining JS and TS). How would one go about implementing the User class, on my rather naive approach, without the JS?
Want to be able to IUserModel without the baggage.
import {IUser} from './user.ts'; import {Document, Schema, Model} from 'mongoose'; // mixing in a couple of interfaces interface IUserDocument extends IUser, Document {} // mongoose, why oh why '[String]' // TODO: investigate out why mongoose needs its own data types let userSchema: Schema = new Schema({ userName : String, password : String, firstName : String, lastName : String, email : String, activated : Boolean, roles : [String] }); // interface we want to code to? export interface IUserModel extends Model<IUserDocument> {/* any custom methods here */} // stumped here export class User { constructor() {} }
To get started with Mongoose in TypeScript, you need to: Create an interface representing a document in MongoDB. Create a Schema corresponding to the document interface. Create a Model.
A Schema represents an ECSchema in TypeScript. It is a collection of Entity-based classes. See the BIS overview for how ECSchemas are used to model information. ECSchemas define classes for models, elements, and aspects, as well as ECRelationships.
js applications to connect to MongoDB and work with data. On the other side Mongoose it other library build on top of mongoDB. It is more easier to understand and use. If you are a beginner than mongoose is better for you to work with.
Types. ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.
Here's how I do it:
export interface IUser extends mongoose.Document { name: string; somethingElse?: number; }; export const UserSchema = new mongoose.Schema({ name: {type:String, required: true}, somethingElse: Number, }); const User = mongoose.model<IUser>('User', UserSchema); export default User;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With