Everyday Dev System

0519_TIL : 파이썬 MongoDB 연동 본문

내배캠 주요 학습/TIL : Today I Learned

0519_TIL : 파이썬 MongoDB 연동

chaeyoung- 2023. 5. 23. 12:01

 

# 문제점 :

각 팀원들의 DB를 참조하기 위해서 table명을 변수로 받아 해당 변수의 테이블에 접근하는데에 어려움을 겪었습니다. 

 

# 시도 : 

createCollection() 메서드도 사용해보았지만, 이미 존재한다고 에러가 떠서 해결되지 않았다.

두번째로 getCollection() 메서드로 해보니 깔끔하게 해결됐다!!!

 

 

 

# 해결방법 :

db.members.insert_one(doc)

예를 들어 members라는 테이블에 접근하기 위한 상단의 코드를

tableName = "members"
db.tableName.insert_one(doc)

이와 같은 코드로는 실행이 되지 않습니다.

이유는 tableName이라는 변수는 현재 String 타입이고, 테이블명이 들어갈 자리에는 collection이기 때문입니다.

tableName = "members"
db.get_collection(tableName).insert_one(doc)

이와 같이 변경하여 해결 하였습니다.

db.get_collection()을 이용하여 db를 참조할 수 있음을 새롭게 알게되었습니다.

 

ProjectCode의 일부 발췌

# 방명록 데이터 DB에 저장
@app.route("/api/comment-save", methods=["POST"])
def comment_post():
    #commentId_receive = request.form['commentId_give']
    commentName_receive = request.form['commentName_give']
    commentContent_receive = request.form['commentContent_give']
    commentPassword_receive = request.form['commentPassword_give']
    islandId = request.form['islandId_give']

    date = str(datetime.now().strftime('%Y-%m-%d %H:%M'))
    
    doc = {
        #'commentId':commentId_receive,
        'commentName' : commentName_receive,
        'commentContent' : commentContent_receive,
        'commentPassword' : commentPassword_receive,
        'commentDate' : date}
    
    print(islandId)
    # 본인 table명으로 변경해주세요
    tableStr = islandId + "_post"
    
    db.get_collection(tableStr).insert_one(doc)
    return jsonify({'msg':'아일랜드에 발자취를 남겼다!'})