[Problem]
과제 진행 중 postId와 commentId를 임의로 부여해야 한다는 것을 깨달았다....
이제는 두렵지 않다. 나에게는 Google 선생님이 계신다...
[Try]
처음 찾아본 것은 ObjectId를 임의로 부여하는 방법이라 검색했다. mongoDB에 올라온 내용을 확인했다.
https://www.mongodb.com/docs/manual/reference/method/ObjectId/
ObjectId() — MongoDB Manual
Docs Home → MongoDB Manual ObjectId( )Returns a new ObjectId. The 12-byte ObjectId consists of:A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch.A 5-byte random value generated once per process. This rando
www.mongodb.com
내용은 ObjectId를 생성하는 방법이다.
But 생각을 해보니 DB에 따로 작업을 안하고 저장할 경우 _Id로 들어온 값들을 임의로 Id를 부여하여 정리해준다는 것을 깨달았다. 따라서 현재 사용하고 mongoose를 이용해 부여하는 방법을 찾아봤다.
mongoose를 검색하여 사이트에 들어갔다. 나는 현재 schema를 쓰고 있으므로 Guides에 schema 문서를 확인했다.
원하는 내용이 없었다. 밑에 schemaTypes가 있어서 이 문서도 읽었다.
https://mongoosejs.com/docs/schematypes.html
Mongoose v7.1.0: SchemaTypes
SchemaTypes handle definition of path defaults, validation, getters, setters, field selection defaults for queries, and other general characteristics for Mongoose document properties. You can think of a Mongoose schema as the configuration object for a Mon
mongoosejs.com
mongoose에 schema types를 이용해 Id를 부여하는 방법을 찾게 되었다.
[Solution]
https://stackoverflow.com/questions/8111846/how-to-set-objectid-as-a-data-type-in-mongoose
How to set ObjectId as a data type in mongoose
Using node.js, mongodb on mongoHQ and mongoose. I'm setting a schema for Categories. I would like to use the document ObjectId as my categoryId. var mongoose = require('mongoose'); var Schema =
stackoverflow.com
const mongoose = require("mongoose");
const postId = new mongoose.Types.ObjectId();
위와 같이 작성할 경우 _Id와 같은 값을 postId에 부여해준다.
[Conclusion]
게시글이나 댓글같은 것에 중복을 처리하고 싶어 Id를 부여하고 싶다면 schema types을 이용하면 된다는 것을 알게되었다. 작성시 중요한 것은
const mongoose = require("mongoose");
이 부분을 놓치면 안 된다.
'Self Dev. > TIL' 카테고리의 다른 글
2023.05.11 TIL - Sequelize (timestamp) (0) | 2023.05.11 |
---|---|
2023.05.07 TIL - MySQL 데이터베이스 (Sequelize를 이용하여 Drop하기) (0) | 2023.05.07 |
2023.04.26 TIL - MongoServerError: E11000 duplicate key error collection (1) | 2023.04.27 |
2023.04.24 TIL - 환경마다 다른 명령어 (0) | 2023.04.24 |
2023.04.19 TIL - 동그라미 엑스로 숫자를? (0) | 2023.04.19 |