我有一個用戶模型,如下所示:
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
minlength: 3,
maxlength: 30,
validate: {
validator: function(v) {
return /^[a-zA-Z0-9] $/.test(v);
},
message: "Your user name must be alphanumeric."
},
unique: true
},
email: {
type: String,
required: true,
validate: {
validator: function(v) {
return /(?:[a-z0-9!#$%&'* /=?^_`{|}~-] (?:\.[a-z0-9!#$%&'* /=?^_`{|}~-] )*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.) [a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f]) )\])/.test(v);
},
message: "Invalid e-mail address."
},
unique: true
},
password: {
type: String,
required: true,
minlength: 4,
maxlength: 1024
},
isAdmin: {
type: Boolean,
default: false
},
devices: [{
type: mongoose.SchemaTypes.ObjectId,
ref: 'Device'
}],
joinDate: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', userSchema);
我有一個users.jsExpress.js 路由器來管理用戶。這些路由之一使用指定的用戶 ID 更新現有用戶。這是路線:
// Modify a user's profile
router.put('/:userId', [auth, authAdmin], async function(req, res, next) {
if(!isValidObjectID(req.params.userId)) return res.status(400).send({ message: 'Given ID is not valid.', status: 400 });
const { error } = validate(req.body);
if(error) return res.status(400).send({ message: error.details[0].message, status: 400 });
let user = await User.findOne({ email: req.body.email });
if(user && user._id && user._id != req.params.userId) return res.status(400).send({ message: 'E-mail address is already in use.', status: 400 });
user = await User.findOne({ username: req.body.username });
if(user && user._id && user._id != req.params.userId) return res.status(400).send({ message: 'Usename is already in use.', status: 400 });
user = await User.findById(req.user._id);
user.username = req.body.username;
user.email = req.body.email;
if(req.body.isAdmin) user.isAdmin = req.body.isAdmin;
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(req.body.password, salt);
try {
user = await user.save();
return res.send(_.omit(user.toObject(), 'password'));
} catch(exception) {
console.log('Put 1:', exception);
}
});
當我使用此路由更新現有用戶的唯一用戶名時,MongoServerError: E11000 duplicate key error collection: iotapi.users index: email_1 dup key: { email: "[email protected]" }出現錯誤。有什么說不通的。我還有另一條路線供用戶更新他們的電子郵件地址。除了更新用戶名外,該路由幾乎具有相同的功能。它作業得很好,但是當我更新用戶名和電子郵件時,它會引發錯誤。
我也嘗試使用.findOneByIdAndUpdate()方法來更新檔案,但沒有成功。我得到了同樣的錯誤。
uj5u.com熱心網友回復:
有一個錯字
user = await User.findById(req.user._id);
應該
user = await User.findById(req.params.userId);
更新
好吧,不是打字錯誤,而是真正的錯誤。
在條件
let user = await User.findOne({ email: req.body.email });
if(user && user._id && user._id != req.params.userId)
僅當具有給定電子郵件的用戶存在且其 ID 與查詢字串中發送的 ID不同時,您才回傳 400 。換句話說,當 Id 相同時,代碼會繼續。
然后您到達從 auth 會話加載用戶的行:
user = await User.findById(req.user._id);
此 ID 可能與請求中發送的 ID 不同,因此您嘗試使用其他用戶的電子郵件更新它。它導致重復錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/388145.html
