我正在制作一個簡單的用戶注冊網路應用程式。我正在使用 MongoDB 和 Express JS 注冊新用戶并將其保存在資料庫中。
我在模式中放置了一些驗證屬性,每當用戶填寫不遵循模式的無效資料時,控制臺中都會顯示驗證錯誤。
現在,我想要做的是寫在控制臺中的驗證錯誤有兩個我想要的屬性,它們是“路徑”和“種類”,所以我可以在瀏覽器中顯示這兩個屬性供用戶使用看。
如何從錯誤物件中獲取“路徑”和“種類”屬性?我不想列印整個錯誤訊息,我只想要這兩個屬性。
我嘗試使用console.log(err.path)and console.log(err.kind),但它們都回傳未定義。
我不知道如何訪問這兩個屬性。
// Post new user (REGISTER):
router.post('/signup', async (req, res) => {
const username = req.body.username;
const email = req.body.email;
const password = req.body.password;
try {
await User.create({username, email, password})
}
catch(err) {
// I don't want the whole err, I just want err.path and err.kind if possible!
console.log(err);
}
});

uj5u.com熱心網友回復:
以下應該作業。這些屬性位于嵌套物件中,由關鍵字保存errors
console.log(err.errors.username.kind, err.errors.username.path)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/460142.html
標籤:javascript 猫鼬
