웹/MongoDB

[mongoDB] 몽고DB updateOne()

ohojee 2023. 8. 17. 02:14

로그인 시 비밀번호를 까먹었을 때 비밀번호 재설정하는 기능을 구현하고 있었다
새로운 비밀번호를 적용하는데에는 두가지 방법이 있는 것 같았다
user.password= hash.updateOne()
전자는 이미 찾아놓은 user 객체에서의 password를 바꿀 수 있는 것 같고
후자는 괄호 안에 찾는 객체의 조건을 넣을 수 있어 검색 후 그에 해당하는 객체의 데이터를 바꿀 수 있는 것 같다
 
나는  .updateOne()을 사용하기로 했다

const result = await User.updateOne(
	{ 'auth.token': `${ token }` }
	{ $set: { password: await bcrypt.hash(new_password, saltRounds) } }
    )
res.status(200).json({ reset_password_success: true, user: result });

auth.token은 sql에서의 where절과 같은 조건이고
$set은 password를 bcrypt.hash(new_password, saltRounds)값으로 변경하겠다는 것이다
이걸 실행하고 나면

업데이트를 실행한 결과가 뜬다
acknowledge가 false로 뜬다면 바꾸지 못했거나 바꿀 객체를 찾지 못한 것이다
 

const user = await User.findOne({ 
    'auth.token': `${ token }`, 
    'auth.created': { $lt: Date.now() - 300 } 
});
if (!user) {
    return res.json({ existingToken: false });
}
const result = await User.updateOne(
    { $set: { password: await bcrypt.hash(new_password, saltRounds) } }
)
res.status(200).json({ reset_password_success: true, user: result });

내 전체 코드는 이러했는데 updateOne에서 따로 조건을 지정해주지 않아도 업데이트가 잘 됐다
생각해본 바로는 이미 앞의 findOne에서 하나의 객체만을 찾았기 때문에 그런 것 같다
 
---
 
아니다. 저렇게 쓰면 업데이트 안 된다.

const result = await User.updateOne(
    { _id: `${ user._id }` },
    { $set: { 'password': await bcrypt.hash(new_password, saltRounds) } }
)

이렇게 써야 제대로 업데이트 된다.
 
참고 자료
https://www.mongodb.com/docs/manual/tutorial/update-documents/

Update Documents — MongoDB Manual

Docs Home → MongoDB Manual ➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples.Starting in MongoDB 4.2, MongoDB can accept an aggregation pipeline to specify the modifications to make instead o

www.mongodb.com