mongoose+TypeScriptでハマりました
mongoose+TypeScriptでハマりました
3時間ぐらい苦戦
結論
mongooseドキュメントにしっかり書いてました。
参考に書いてみたのが、こちら
import { model, Schema } from "mongoose";
interface User {
username : String ;
email : String ;
password : String ;
profileImage? : String ;
coverImage? : String ;
followers : Array<Number> ;
followings : Array<Number> ;
isAdmin : Boolean ;
description : String ;
city : String ;
}
//データ構造
const userSchema = new Schema<User>(
{
username: {
type : String ,
require : true ,
min : 2 ,
max : 25 ,
//unique: trueで名前の重複を防ぐ
unique : true ,
},
email : {
type : String ,
require : true ,
max : 50 ,
unique : true ,
},
password: {
type : String ,
require : true ,
min : 5 ,
max : 30 ,
},
profileImage: {
type : String ,
default : "" ,
},
coverImage : {
type : String ,
default : "" ,
},
followers : {
types : Array ,
default : [] ,
},
followings : {
types : Array ,
default : [] ,
},
//*権限があるかないか、認証済みか認証済みでないかの判定<-重要
isAdmin : {
type : Boolean,
default : false ,
},
//プロフィールの概要
description : {
type : String ,
max : 50 ,
},
city : {
type : String ,
max : 50 ,
},
},
//日時を自動的に格納
{timestamps: true}
);
export const User = model<User>('User', userSchema);
mongooseのSchemaでデータ構造を作成
ドキュメント インターフェイスが Mongoose スキーマと一致していることを確認する責任がありますとのこと。
つまり明示する必要があっただけなんかな。。。
学んだこと
エラー文をコピって情報サイトで調べるのはもちろんですが、まずはドキュメントを見に行くことが
大事だと感じました。