【问题标题】:Mongodb doesn't updateMongoDB不更新
【发布时间】:2021-02-23 14:01:17
【问题描述】:

我正在尝试在 mongodb 中更新我的数据中的配置文件用户,但它没有更新,它也没有在我的控制台中返回错误..

这是我的功能:

function editPassword(e) {
    e.preventDefault();

    fetch(`${process.env.NEXT_PUBLIC_API_URL}/users/update`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({
            firstName: firstName,
            lastName: lastName,
            email: email,
            password: password1
        })
    })
    .then(res => {
        return res.json()
    })
    .then(data => {
        console.log(data)
        if(data === true) {
            Swal.fire({
                title: "Account updated.",
                icon: "success",
            })
            Router.push('/')
        } else {
            Router.push('/error')
        }
    })
}

这是路线:

router.put('/update', auth.verify, (req, res) => {
    UserController.editPassword(req.body)
    .then(resultFromUpdate => res.send(resultFromUpdate))
})

这是控制器:

module.exports.editPassword = (params) => {
        const updates = {
            firstName: params.firstName,
            lastName: params.lastName,
            email: params.email,
            password: bcrypt.hashSync(params.password, 10)
        }

        return User.findByIdAndUpdate(params.userId, updates).then((updated, err) => {
            return (err) ? false : true
        })
}

任何帮助将不胜感激。

【问题讨论】:

  • 你和mongodb连接成功了吗?
  • @UmairRiaz 是的,它说“现在已连接到 mongodb atlas”
  • User.findOneAndUpdate({userId: params.userId}, { $set: updates }, { new: true }).then((updated, err) => {return (err) ? false : true})
  • @UmairRiaz 非常感谢!!它现在正在工作..你认为我的代码有什么错误?

标签: node.js reactjs api


【解决方案1】:

请使用findOneAndUpdate 并将$set 用于patchnew 用于返回更新的有效负载。

User.findOneAndUpdate({userId: params.userId}, { $set: updates }, { new: true })
  .then((updated, err) => {return (err) ? false : true})

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2018-11-08
    • 2020-08-29
    • 2017-12-14
    • 2015-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多