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,用户名:string,密码:string等。
我向此路由发送一个如下所示的json来更改其用户名
{"username": "Admin123"}
假设Admin123不存在,则const foundUser
不会为null,因为用户集中没有用户名为Admin123的用户。但是const foundUser永远不会为null?我不确定自己在做什么错
答案 0 :(得分: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');
}
})