试图在Typescript中实现Mongoose模型.搜索谷歌只揭示了混合方法(结合JS和TS).在没有JS的情况下,如何以我天真的方式实现User类?
希望能够在没有行李的情况下使用IUserModel.
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{/* any custom methods here */} // stumped here export class User { constructor() {} }
Louay Alakka.. 83
我是这样做的:
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('User', UserSchema); export default User;
`import*as mongoose来自'mongoose';`或`import mongoose = require('mongoose');` (6认同)
最后一行(导出默认const用户...)对我不起作用.我需要拆分该行,如http://stackoverflow.com/questions/35821614/typescript-compile-error-error-ts1109-expression-expected中提出的那样 (3认同)
我可以做“ let newUser = new User({iAmNotHere:true})”,而不会在IDE中或编译时出现任何错误。那么创建接口的原因是什么? (3认同)
抱歉,在TS中如何定义“猫鼬”? (2认同)
Gábor Imre.. 24
如果要分离类型定义和数据库实现,则另一种方法.
import {IUser} from './user.ts'; import * as mongoose from 'mongoose'; type UserType = IUser & mongoose.Document; const User = mongoose.model('User', new mongoose.Schema({ userName : String, password : String, /* etc */ }));
来自这里的灵感:https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models
我是这样做的:
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('User', UserSchema); export default User;
如果要分离类型定义和数据库实现,则另一种方法.
import {IUser} from './user.ts'; import * as mongoose from 'mongoose'; type UserType = IUser & mongoose.Document; const User = mongoose.model('User', new mongoose.Schema({ userName : String, password : String, /* etc */ }));
来自这里的灵感:https://github.com/Appsilon/styleguide/wiki/mongoose-typescript-models
对不起,但这对某人来说仍然很有趣.我认为Typegoose提供了更现代和更优雅的方式来定义模型
以下是文档中的示例:
import { prop, Typegoose, ModelType, InstanceType } from 'typegoose'; import * as mongoose from 'mongoose'; mongoose.connect('mongodb://localhost:27017/test'); class User extends Typegoose { @prop() name?: string; } const UserModel = new User().getModelForClass(User); // UserModel is a regular Mongoose Model with correct types (async () => { const u = new UserModel({ name: 'JohnDoe' }); await u.save(); const user = await UserModel.findOne(); // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 } console.log(user); })();
对于现有的连接方案,您可以使用如下(在实际情况中可能更有可能并在文档中发现):
import { prop, Typegoose, ModelType, InstanceType } from 'typegoose'; import * as mongoose from 'mongoose'; const conn = mongoose.createConnection('mongodb://localhost:27017/test'); class User extends Typegoose { @prop() name?: string; } // Notice that the collection name will be 'users': const UserModel = new User().getModelForClass(User, {existingConnection: conn}); // UserModel is a regular Mongoose Model with correct types (async () => { const u = new UserModel({ name: 'JohnDoe' }); await u.save(); const user = await UserModel.findOne(); // prints { _id: 59218f686409d670a97e53e0, name: 'JohnDoe', __v: 0 } console.log(user); })();
尝试ts-mongoose
。它使用条件类型进行映射。
import { createSchema, Type, typedModel } from 'ts-mongoose';
const UserSchema = createSchema({
username: Type.string(),
email: Type.string(),
});
const User = typedModel('User', UserSchema);
只需添加另一种方式:
import { IUser } from './user.ts'; import * as mongoose from 'mongoose'; interface IUserModel extends IUser, mongoose.Document {} const User = mongoose.model('User', new mongoose.Schema({ userName: String, password: String, // ... }));
之间的差异interface
,并type
请阅读此答案
这种方式有一个优点,你可以添加Mongoose静态方法类型:
interface IUserModel extends IUser, mongoose.Document { generateJwt: () => string }
如果您已经安装 @types/mongoose
npm install --save-dev @types/mongoose
你可以这样
import {IUser} from './user.ts'; import { Document, Schema, model} from 'mongoose'; type UserType = IUser & Document; const User = model('User', new Schema({ userName : String, password : String, /* etc */ }));
PS:复制@Hongbo Miao
的答案