Node.js NodeJS Mongoose updateOne每次都不匹配
我正在尝试使用updateOne方法用mongoose更新mongo中的文档:Node.js NodeJS Mongoose updateOne每次都不匹配,node.js,mongoose,Node.js,Mongoose,我正在尝试使用updateOne方法用mongoose更新mongo中的文档: const updateResult = await UserModel.updateOne({ _id: mongoose.Types.ObjectId(userId) }, { $set: { a: 'B' } }) userId包含用户ID的字符串 我试过使用以下方法 1. { _id: userId } 2. { email: theE
const updateResult = await UserModel.updateOne({
_id: mongoose.Types.ObjectId(userId)
}, {
$set: {
a: 'B'
}
})
- userId包含用户ID的字符串
1. { _id: userId }
2. { email: theEmailOfTheUser }
但是,updateResult仍然是
n:0, nModified:0, ok:0
所以我认为这一定是方法本身的问题,而不是在我的查询中
另外,当我尝试使用下面的查询查找用户时,它可以找到它:
const user = await UserModel.find({
_id: userId
});
//user is found
实际上,mongoose负责
$set
,您不必添加它。只是:
const updateResult = await UserModel.updateOne({
_id: userId
}, {
a: 'B'
})
但是更好的解决方案是只使用findByIdAndUpdate()
:
谢谢,如果我必须$push怎么办?我想你必须先找到文档并手动更新它。实际上$push按预期工作(而不是$set)nice:D不知道!
const updateResult = await UserModel.findByIdAndUpdate(userId, {
a: 'B'
})