簡體   English   中英

我怎樣才能只更新我想要的那個屬性?

[英]How can I update only that attribute which I want to?

你怎么看,它工作正常,但只有當我輸入所有內容時它才能工作。

因此,例如,我只想更改我的密碼,我該如何實現。

你知道在我的前端我的用戶ID總是被給出並且不能更新如果它很重要我不會

我的更新 function:

exports.update = async (req,res,next) => {

  try {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(req.body.password, salt);

      const result = await User.findOneAndUpdate(
          {
              userID: req.body.userID,
          },
          {
              userName: req.body.userName,
            
          },
          {
            password: hashedPassword
          },
          
          {
              upsert: true,
              new: true
          }
      )
      res.send(result);
  }catch(err){
      res.status(401).json(err);
  }
}

我如何要求它:

###
PUT http://localhost:8080/user/
Authorization: Bearer {{token}}
Content-Type: application/json

{

     "userID": "test",
    "userName": "test",
    "password": "12345"
    

}

但我想要的可能只有這個:

###
PUT http://localhost:8080/user/
Authorization: Bearer {{token}}
Content-Type: application/json

{

     "userID": "",
    "userName": "",
    "password": "12345"
    

}

如果您只想更新密碼,並且由於我假設您的 userId 是唯一的,那么就這么簡單:

const result = await User.findOneAndUpdate(
          {
              userID: req.body.userID,
          },
          {
            password: hashedPassword
          },
          
          {
              upsert: true,
              new: true
          }
      );

EDIT: the prototype of findOneAndUpdate function takes 2 mandatory parameters and two optionals, in order: filter , and object used in the find part of the function, update , an object with the keys to update for the object found, and options where you can指定一堆選項(如upsertnew )。 最終,可以給它一個回調,但你已經在使用 async/await 所以它不是那么有用......

請注意,此 function只會更新您在update參數中提供的內容,因此對於您的評論,我的代碼仍然有效。 在這里閱讀更多。 function 的原型也在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM