[항해99] 43일차 API완성 JWT토큰 , populate, ref mongoose

IT/Bootcamp 항해99|2021. 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://web.postman.co/documentation/16410236-9482adef-a3a9-467e-b27c-10e3d4ddd9df/publish?workspaceId=d9737e56-54dc-463c-8c81-757392c75b0f 

 

https://fierycoding.tistory.com/35

 

mongoose로 relation 설정하기 (populate 이용하기)

mongodb는 관계형 데이터베이스들과 다르게 모델끼리의 관계를 직접 설정할 수 없습니다. 하지만 다른 documents들이 서로를 참조할 수 있게끔 설정할 수 있습니다. mongodb와 node.js의 ODM인 몽구스를

fierycoding.tistory.com

https://velog.io/@nomadhash/MongoDB-Mongoose%EC%9D%98-populate%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%ED%83%80-collection-%EC%B0%B8%EC%A1%B0

 

[사이드 프로젝트] Mongoose의 'populate'를 이용한 타 collection 참조 👀

NoSQL 데이터 베이스인 MongoDB를 사용하다보면, 컬렉션의 특정 데이터를 기반으로 다른 컬렉션의 데이터를 참조할 일이 생긴다. 그러나 관계형 데이터 베이스처럼 테이블 join을 할 수는 없는 상황

velog.io

 

반응형

댓글()