[항해99] 43일차 API완성 JWT토큰 , populate, ref mongoose
IT/Bootcamp 항해992021. 7. 20. 01:52
항해 99
43일차 :
클론코딩 오늘까지API를 다만들고 서버배포까지 할생각을 했었는데, 역시나 이쯤되서 발견되는 여러가지 문제들을 하나씩 해결하기위해 11시가 다되어서 레드불을 마셧다. 물론3시에 쯤에는 이자리에서 꼬꾸라져서 잠들겠지만... 할수있는데까지 해봐야겠다.
1. 이렇게 New User 로 만드는방식과 2. Model.Create 이랑 뭐가다른걸까?
router.post('/', async (req, res) => {
// comments writer info get from token
const user = new User(req.body);
try {
await user.save();
await res.status(201).send(user);
} catch (err) {
res.status(400).send(err);
}
});
2. SQL 에는 관계설정으로인해 나중에 불러오기가 편한데, 몽고db 는 관계설정이없는걸까 하고 찾다가
populate와ref 쪽을 찾게되었다.
더보기
일단 test용으로 두개의 Schema를 만들어봤다:
cars.js에서 ownerId 부분에 type 이무조건 Schema.Types.ObjectId로 되어있어야한다!
그리고ref에 참조할 schema 부분을 적어놔야 연결이된다.
cars.js
const mongoose = require("mongoose")
const { Schema } = mongoose
const CarSchema = new Schema({
_id: Schema.Types.ObjectId,
carId: Number,
brand: String,
model: String,
ownerId: {
type: Schema.Types.ObjectId,
ref: 'Owner',
required: true
}
})
module.exports = mongoose.model('Car', CarSchema)
owners.js
const mongoose = require("mongoose")
const { Schema } = mongoose
const OwnerSchema = new Schema({
_id: Schema.Types.ObjectId,
ownerId: Number,
name: String,
})
module.exports = mongoose.model('Owner', OwnerSchema)
api:
const express = require("express");
//const { Mongoose } = require("mongoose");
const mongoose = require("mongoose")
const router = express.Router()
const Car = require("../schemas/cars");
const Owner = require('../schemas/owners')
router.get("/noPopulate", async (req, res) => {
const allCar = await Car.find({})
res.json(allCar)
})
router.get("/populate", async (req, res) => {
const allCar = await Car.find({}).populate("ownerId")
res.json(allCar)
})
router.post("/createCar", async (req, res) => {
const cars = await Car.find({})
const carId = cars.length + 1
const { brand, model } = req.body
const owners = await Owner.find({})
const ownerId = owners[0]._id
const _id = new mongoose.Types.ObjectId()
const testCase = await Car.create({ brand, model, ownerId, _id })
res.send("ok")
})
router.post("/createOwner", async (req, res) => {
const { ownerId, name } = req.body
const _id = new mongoose.Types.ObjectId()
const newOwner = await Owner.create({ ownerId, name, _id })
res.send("ok")
})
module.exports = router
밑에 postman에서 확인할수있겟지만, 나중에
populate("ownersId") 이걸로 연결된부분의 데이터를 가져올수있다.
populate없이 가져오게된다면, data가 ownerId(연결한부분)이 그냥 object값으로 나온다.
populate을 넣어서 실행한다면,
ownerId가 해당 하는부분을 모두 가져오는것을 확인할수있다.
그러면 이것을 이용해서 글과 해당글에 댓글을 가져올수잇다!!
https://fierycoding.tistory.com/35
반응형
'IT > Bootcamp 항해99' 카테고리의 다른 글
[항해99] 45일차 클론코딩 (6) | 2021.07.21 |
---|---|
[항해99] 44일차 몽구스 populate (0) | 2021.07.21 |
[항해99] 42일차 API설계와 포스트맨 사용법 (0) | 2021.07.18 |
[항해99] 40일 & 41일차 클론코딩 (3) | 2021.07.18 |
[항해99] 39일차 (0) | 2021.07.15 |
댓글()