簡體   English   中英

findOne 不工作? mongoose / mongodb 服務器

[英]findOne not working? mongoose / mongodb server

app.post("profile/:id", (req, res) => {
    const id = req.params.id



    User.findById(id).then((user) => {
        if (!user) {
            res.status(404).send('Resource not found')
        } else {
            const keys = Object.keys(req.body)
            keys.forEach(key => {
                if (key === "username") {
 
                   const foundUser = User.findOne({ "username": req.body.username })

                   if (foundUser === null)
                        user.username = req.body.username
                    
                }



            })
            user.save()




        }
    })
        .catch((error) => {
            log(error)
            res.status(500).send('Internal Server Error')  // server error
        })

});

基本上用戶有屬性 {_id: objectid, username: string, password: string, .. etc}

我向這條路線發送 json 如下所示以更改其用戶名

{"username": "Admin123"}

假設 Admin123 不存在,則const foundUser不會是 null,因為用戶集合中沒有用戶名為 Admin123 的用戶。 但是 const foundUser 永遠不是 null? 我不確定我做錯了什么

干草,我給你一個更小的解決方案怎么樣,只是為了讓你的代碼更好

你的代碼有什么問題??

  • 您正在查詢同一個用戶兩次!
  • 你在回調函數的山上
  • 當您知道用戶確實有“用戶名”時循環用戶
  • 不應該直接使用保存方法。

您應該首先檢查是否存在具有相同用戶名的用戶! 您應該返回重復的或不允許的或已經存在的

您應該使用 mongoose 或任何其他數據庫中的查詢功能,因為它更快
閱讀下面的代碼,如果您不明白,我會幫助您。 隨時評論或通過 fb.com/mustafa.ali2 聯系我

// I'm using here async await which is much cleaner and easy to read 😄
app.post('profile/:id', async (req, res) => {
  // Try catch for any error other error 😇
  try {
    // Destructuring the id form req.params (new way to do things !)
    const { id } = req.params
    // Querying the DB (MongoDB) and updating when we fond the user that match the given _id 😉
    const user = await User.findOneAndUpdate(
      { _id: new mongoose.Types.ObjectId(id), username: null },
      { $set: { username: req.body.username } }
    )
    // if user not found return error 🙂
    if (!user)
        return res.status(404).send('Resource not found');
    // if user found return success 🙂
    res.status(200).send('Updated successfully');
  } catch (err) {
    log(err);
    res.status(500).send('Internal Server Error');
  }
})

暫無
暫無

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

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