Can anyone help me solve this problem, I've been stuck days on it and haven't found any solution to. I have this user schema in my 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],
});
The helpSent is basically an array that stores every data the user has requested in the application.
Now by using my update function, which is the following:
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});
}
}
I'm getting this error as if the function is storing a new data entry in the database and telling me that the username is already taken since I have it as a unique value
{
message: Error: user validation failed: _id: Username already in use.
at ValidationError.inspect (D:\Patrick\Flutter\Fyp\draft-v1\backend\node_modules\mongoose\lib\error\validation.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'
}
}
Anyone help can help, and thank you!
CodePudding user response:
Why dont you use updateOne
await User.updateOne({ username: decoded.data }, {
$push: {
helpSent: help
}
})
The first argument is the query condition, in your case you search for an username with decoded.data
, and the second argument is your update logic