有谁能帮我解决这个问题吗?我已经被困了好几天了,还没有找到任何解决方案。我有这个用户模式在我的mongodb/node js:
const userSchema = new Schema({
username:{
type: String,
required: true,
unique: true,
},
name:{
type: String,
required: true,
},
password:{
type: String,
required: true,
},
phoneNumber:{
type: String,
required: true,
},
age:{
type: Number,
required: true,
},
helpSent: [Help.schema],
});
helpSent基本上是一个数组,用于存储用户在应用程序中请求的所有数据。
现在使用我的更新函数,如下所示:
exports.createHelp = async (req,res) => {
try{
const decoded = jwt.verify(req.headers.authorization.split(' ')[1], config.secret);
const help = new Help({
type: req.body.type,
description: req.body.description,
timeToRespond: req.body.timeToRespond,
emergencyLevel: req.body.emergencyLevel,
acceptance: req.body.acceptance,
state: req.body.state,
dateIssued: req.body.dateIssued
});
const user = await User.findOne({username: decoded.data});
user.helpSent.push(help);
const savedUser = await user.save();
res.json(savedUser)
}catch(e){
console.log({message: e});
}
}
我得到这个错误,如果函数在数据库中存储一个新的数据条目,并告诉我用户名已经被占用,因为我有它作为一个唯一的值
{
message: Error: user validation failed: _id: Username already in use.
at ValidationError.inspect (D:PatrickFlutterFypdraft-v1backendnode_modulesmongooseliberrorvalidation.js:48:26)
at formatValue (node:internal/util/inspect:763:19)
at formatProperty (node:internal/util/inspect:1681:11)
at formatRaw (node:internal/util/inspect:1006:9)
at formatValue (node:internal/util/inspect:793:10)
at inspect (node:internal/util/inspect:340:10)
at formatWithOptionsInternal (node:internal/util/inspect:2006:40)
at formatWithOptions (node:internal/util/inspect:1888:10)
at console.value (node:internal/console/constructor:323:14)
at console.log (node:internal/console/constructor:359:61) {
errors: { _id: [ValidatorError] },
_message: 'user validation failed'
}
}
任何人都可以帮忙,谢谢!
为什么不使用updateOne
await User.updateOne({ username: decoded.data }, {
$push: {
helpSent: help
}
})
第一个参数是查询条件,在本例中使用decoded.data
搜索用户名,第二个参数是更新逻辑