Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose the Typescript way...?

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() {} } 
like image 621
Tim McNamara Avatar asked Dec 27 '15 15:12

Tim McNamara


People also ask

Does Mongoose work with TypeScript?

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.

What is a schema TypeScript?

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.

Is Mongoose better than MongoDB?

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.

What is Mongoose types ObjectId?

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.


1 Answers

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; 
like image 195
Louay Alakkad Avatar answered Sep 29 '22 03:09

Louay Alakkad