誰能幫我解決這個問題,我已經被困了好幾天了,還沒有找到任何解決方案。我的 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:\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'
}
}
任何人都可以提供幫助,謝謝!
uj5u.com熱心網友回復:
你為什么不使用updateOne
await User.updateOne({ username: decoded.data }, {
$push: {
helpSent: help
}
})
第一個引數是查詢條件,在您的情況下,您使用 搜索用戶名decoded.data,第二個引數是您的更新邏輯
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/489687.html
