【问题标题】:findOne not working? mongoose / mongodb serverfindOne 不工作?猫鼬 / mongodb 服务器
【发布时间】:2020-08-07 08:45:56
【问题描述】:
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 不会为空,因为用户集合中没有用户名为 Admin123 的用户。但是 const foundUser 永远不会为空?我不确定我做错了什么

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    嘿,我给你一个更小的解决方案怎么样,只是为了让你的代码更好

    你的代码有什么问题??

    • 您查询同一个用户两次!
    • 你在回调函数的山上
    • 当您知道用户确实有“用户名”时循环该用户
    • 不应直接使用保存方法。

    您应该首先检查是否存在具有相同用户名的用户!你应该返回重复的或不允许的或已经存在的

    你应该在猫鼬或任何其他数据库中使用查询功能,因为它更快
    阅读下面的代码,如果您不明白,我会帮助您。 随时评论或通过 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');
      }
    })
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2014-08-12
      • 2018-07-22
      相关资源
      最近更新 更多