【发布时间】: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