-
MongoDB) Expected "payload" to be a plain object 에러 해결법.DB 2020. 5. 6. 12:22
jwt 토큰 발급을 위해 jwt.sign의 payload 부분에 user._id를 넣었더니 아래와 같은 에러가 발생했다.
해결법은 user._id 뒤에 toJSON() 또는 toHexString()을 붙이는 것이다.
ObjectId 클래스는 MongoDB 도큐먼트의 기본키이고, _id 필드에 해당된다.
ObjectId는 12 byte binary BSON 타입으로 12 바이트는 아래와 같이 구성되어 있다.
출처 : https://mongodb.github.io/node-mongodb-native/2.0/tutorials/objectid/ 하지만 npm 문서에 따르면,
If payload is not a buffer or a string, it will be coerced into a string using
JSON.stringify.jwt.sign(payload, secretOrPrivateKey, [options, callback])에 들어가는 payload는 버퍼나 스트링이어야 하므로 _id 필드를 payload로 사용하려면 plain object로 바꿔주는 작업이 필요하다!
toJSON()과 toHexString() 외에도 plain object를 만드는 방법은 다양하다.
출처 : https://stackoverflow.com/questions/52453407/the-difference-between-object-and-plain-object-in-javascript/52453477#52453477 https://www.npmjs.com/package/jsonwebtoken
jsonwebtoken
JSON Web Token implementation (symmetric and asymmetric)
www.npmjs.com
https://mongodb.github.io/node-mongodb-native/2.0/tutorials/objectid/
ObjectId
ObjectId The ObjectId class is the default primary key for a MongoDB document and is usually found in the _id field in an inserted document. Let’s look at an example. { "_id": ObjectId("54759eb3c090d83494e2d804") } An ObjectId is a 12 byte binary BSON type
mongodb.github.io