LoginSignup
0
1

More than 3 years have passed since last update.

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

Posted at

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

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


const pet = {
   name: 'Doggy'
}

console.log(JSON.stringify(pet))


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

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

const pet = {
   name: 'Doggy'
}

pet.toJSON = function(){
  return {}
}

console.log(JSON.stringify(pet))


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

つまり

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

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

//mongooseを利用して、データベース型を設定
const mongoose = require('mongoose')
const userSchema = new mongoose.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(){
  const user = this
  const userObject = user.toObject()

  delete userObject.password
  delete userObject.tokens


  return userObject
}


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

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1