javascript - Mongoose updateOne() 正常但没有更新
问题描述
我有这个要求:
// PUT that updates a user.
router.put('/api/user/:id', async (req: Request, res: Response) => {
const { email, name, avatar } = req.body
const userId = req.body._id
const conditions = {
_id : userId
}
const user = {$set: { "email": email, "name": name, "avatar": avatar } }
User.updateOne(conditions, user).then(doc => {
if (!doc) { return res.status(404).end() }
return res.status(200).json(doc)
}).catch(error => console.log(error))
})
我从请求中得到了这个响应:
{
"n": 0,
"nModified": 0,
"ok": 1
}
如果您可以在 StackOverflow 上找到有关 mongoose 中的updateOne()
方法的信息,我可能已经尝试过。无论我尝试什么,该文档都不会更新。
编辑:我尝试在查询中使用 ObjectID,结果相同。
编辑2:我想通了。正在使用 req.body.id 而不是 req.params.id 并且我正在使用参数来发送请求。感谢大家的帮助!
解决方案
nModified == 0
表示您没有匹配此 ID 的用户,
您的路线是put /api/user/:id
,但您的用户 ID 在 req.params.id 而不是 req.body._id
推荐阅读
- python - 基于主要标识符的熊猫数据框标签比较
- flutter - SingleChildScrollView 的问题 - Flutter
- android - 如何在 Kotlin 的 Android 上的 WebView 中上传多个文件?
- java - Firebase:为身份验证和通知设置不同的环境
- swiftui - SwiftUI:在渲染之间保留 ObservedObject
- mongodb - MongoDB /AWS documentdb 索引利用率有无限制
- javascript - then(() => { 不要在 TypeScript 中发送值
- c++ - 如何为 mlpack 的 kmeans 构造 HamerlyKmeans 对象
- javascript - 即使在“导出默认值”之后,也无法在没有大括号的情况下导入模块
- azure - 将 Azure 函数作为 Windows 服务运行以进行调试