본문 바로가기

내일배움 캠프/TIL

2023 03 14 pyhton,mongo db 를 이용한 방명록 구축

    last_index=col.find().sort('_id',-1).limit(1)
    if col.count_documents({}) == 0:
        index=1
    else:
        index=last_index[0]['index']+1
    doc={
        'index':index,
        'id':id_receive,
        'pw':pw_receive,
        'comment':comment_receive
    }
    col.insert_one(doc)

야매로 짜버린 게시판 index...  방명록삭제를 구현하기위해 index값을 어떻게하면 구할수있을지 생각을 많이했었다

sort()를 이용해서 _id를 역순으로 정렬한다음에 1개만 가져와서 그 데이터의 인덱스값보다 1높게 인덱스가 들어가게 했다

result = col.find_one({'index':index2,'pw':pw})
    if result is None:
        return jsonify({'msg': '삭제 실패!'})
    else:
        col.delete_one({'index':index2})
        all_data=col.find({'index':{'$gt':index2}})
        for data in all_data:
            current_index = data['index']
            new_index = current_index-1
            col.update_one({'_id': data['_id']},{'$set':{'index':new_index}})
        return jsonify({'msg': '삭제 완료!'})

처음에 구한 인덱스를 이용해서 인덱스값이랑 비밀번호랑 비교를해서 해당데이터를 찾은후에 해당 인덱스값보다 높은 데이터를 가지고있는 데이터들을 읽은다음에 for와 update를 이용해서 삭제된 데이터 이후에 만들어진 데이터들의 인덱스를 수정했다