mongoDB에 식별값(숫자) 부여하여 차례대로 저장하기

Doyeon·2023년 1월 11일

#230111

데이터를 나중에 삭제할 때 번호를 찾아 삭제할 수 있도록, 데이터 넣을 때마다 num 값을 부여해서 저장한다.

doc = {
        'num': idnum,
        'title': title_receive,
        'star': star_receive,
        'comment': comment_receive
    }

처음에는 db에 있는 num 값 중 제일 큰 값을 찾아 1을 더하여 num을 부여하기로 했는데,
이럴 경우 데이터가 아무것도 없을 때 에러가 발생한다.

TypeError: 'NoneType' object is not subscriptable

아무 값이 없는데 1을 더하려고 하니 에러가 난 것이다.
그래서 데이터가 아무것도 들어있지 않다면 idnum에 1을 넣어 그 값을 num에 부여하도록 바꾸었다.

<수정전>

idnum = db.reviews.find_one(sort=[("num", -1)])["num"] + 1

<수정후>

if len(list(db.reviews.find({}, {'_id': False}))) == 0:
    idnum = 1
else:
    idnum = db.reviews.find_one(sort=[("num", -1)])["num"] + 1

doc = {
        'num': idnum,
        'title': title_receive,
        'star': star_receive,
        'comment': comment_receive
    }
profile
🔥

0개의 댓글