我有一個名為 mail 的欄位,它在 MongoDB 中是唯一的。
我正在嘗試更新用戶,但碰巧如果我不更改郵件欄位,它會告訴我它是重復的。我不需要總是更改電子郵件,因為有時他們只想更改另一個欄位。
這是我的模型:
import { Schema, model } from "mongoose";
const UserSchema = Schema (
{
username: {
type: String,
maxlength:50,
required: [true, 'El Nombre de Usuario es obligatorio'],
unique: true
},
name: {
type: String,
maxlength:50,
required: [true, 'El Nombre es obligatorio']
},
lastName: {
type: String,
maxlength:50,
required: [true, 'El Apellido es obligatorio']
},
mail: {
type: String,
required: [true, 'El Correo es obligatorio'],
unique: true
},
password: {
type: String,
required: [true, 'La Contrase?a es obligatorio']
},
picture:{
path: {
type: String
},
originalName: {
type: String
}
},
role: {
type: String,
required: true,
enum: ['ADMIN_ROLE', 'USER_ROLE', 'SUPER_ROLE', 'SELLER_ROLE', 'WAREHOUSE_ROLE', 'WAREHOUSE_ASSISTANT_ROLE', 'SALES_ROLE', 'PURCHASES_ROLE','CASH_ROLE']
},
status: {
type: Boolean,
default: true
},
createdBy:{
uid : { type: String, required: true },
username:{ type: String, required: true }
},
createdAt: {
type: Date,
default: Date.now
}
}
);
module.exports = model('Users', UserSchema);
這是我更新的函式,但它回傳郵件中重復鍵的錯誤。
const updateUser = async (req, res = response) => {
let id = req.params.id;
let { _id, password, ...data } = req.body;
if ( password ) {
let salt = bcrypt.genSaltSync(15);
resto.password = bcrypt.hashSync( password, salt );
}
let lastModificationByUser = {
uid: req.uid,
username: req.user.username,
comments: data.comments
};
let user = await User.findByIdAndUpdate( id,
{
$set: data,
$push: {
'lastModificationBy': {
$each: [lastModificationByUser],
$slice: -5
}
}
},{ new: true }
);
res.json({
user
})
}
但我收到以下錯誤:

謝謝你的幫助。
uj5u.com熱心網友回復:
了解獨特
如果您創建一個具有唯一電子郵件地址的用戶,然后將他們的電子郵件地址更新為非唯一值(相同的電子郵件地址),您將收到 dup key 錯誤。
如果您插入一個電子郵件地址為空的用戶,并嘗試創建另一個電子郵件地址為空的用戶,您也會收到 dup 錯誤。
在你的情況下
從您的物件中洗掉該mail欄位data,除非您使用新的唯一電子郵件地址更新用戶。
不要相信任何提交的客戶端
let { _id, password, ...data } = req.body;
解構然后將data欄位直接更新到模型是不安全的。(例如,即使您的表單不包含密碼欄位)
例如,我可以發送帶有curl或postman帶有password欄位的發布請求,您也會在不知情的情況下更新密碼。
你應該做什么
const { name, lastname, picture } = data;
const update = { name, lastname, picture }
let user = await User.findByIdAndUpdate( id, update );
PS:這只是一個示例,盡管在您的代碼中您已經有條件地檢查了您的密碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/429523.html
標籤:javascript 节点.js mongodb 表示 猫鼬
上一篇:使用Mongoose在.find()上對DD/MM日期進行排序
下一篇:在電子表格中替換/追加資料
