Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8902

toJSONを用いて、JSONデータの返り値を制御する

$
0
0

JSONデータの返り値を制御する

例)petというJSONデータの場合

constpet={name:'Doggy'}console.log(JSON.stringify(pet))


{'name':'Doggy'}
というJSONデータが返ってくる。

★返り値となるJSONデータを、toJSONを使って制御することができる

constpet={name:'Doggy'}pet.toJSON=function(){return{}}console.log(JSON.stringify(pet))


{}
というJSONデータが返ってくる。

つまり

toJSONで上書きされた値が、pet定数のJSONデータとして認識される

データベースのセキュリティ向上に利用

//mongooseを利用して、データベース型を設定constmongoose=require('mongoose')constuserSchema=newmongoose.Schema({name:{type:String,//データ型の設定required:true,trim:true},password:{type:String,required:true,},tokens:[{token:{type:String,require:true}}],})//toJSONを用いて、外からuserObjectにアクセスした時に、返すメソッドと返さないメソッドを決めるuserSchema.methods.toJSON=function(){constuser=thisconstuserObject=user.toObject()deleteuserObject.passworddeleteuserObject.tokensreturnuserObject}


これで、userObjectは、toJSONで指定されている、passwordとtoken以外のデータを返すようになる。


Viewing all articles
Browse latest Browse all 8902