My problem is that I am sending an axios request with certain data, however, not all of the data is being updated in the user model. See my code below:
Front-End code with axios request:
JavaScript
x
133
133
1
import axios from "axios"
2
import { useState } from "react"
3
import { useDispatch, useSelector } from "react-redux"
4
import { changeAddress, changeError, changeNatId, changePhone } from "../../store/contactReducer"
5
import { NavBar } from "../Navbar"
6
7
export const ContactInfoForm = function({nombre, correo, userId, cedula, telefono, direccion}) {
8
const { natId, address, phone, error } = useSelector(({contactReducer}) => ({
9
nationalid: contactReducer.nationalid,
10
address: contactReducer.address,
11
phone: contactReducer.phone,
12
error: contactReducer.error,
13
}))
14
const [edit, setEdit] = useState(false)
15
const dispatch = useDispatch()
16
17
async function handleSubmit(e) {
18
e.preventDefault()
19
20
try {
21
const { data } = await axios({
22
method: 'PUT',
23
baseURL: process.env.REACT_APP_SERVER_URL,
24
url: `/users/user/${userId}`,
25
data: {
26
nationalid: natId,
27
address: address,
28
phone: phone,
29
}
30
})
31
console.log(data)
32
}catch(error) {
33
dispatch(changeError(error))
34
}
35
}
36
37
if(edit === true) {
38
return(
39
<>
40
<NavBar />
41
<form onSubmit={handleSubmit}>
42
<label htmlFor='nombre'>Nombre</label>
43
<p
44
id='nombre'
45
>
46
{nombre}
47
</p>
48
<label htmlFor='correo'>Correo</label>
49
<p
50
id='correo'
51
>
52
{correo}
53
</p>
54
<label htmlFor='cedula'>Cédula</label>
55
<input
56
type='text'
57
id='cedula'
58
onChange={e => dispatch(changeNatId(e.target.value))}
59
/>
60
<label htmlFor='direccion'>Dirección</label>
61
<input
62
type='text'
63
id='direccion'
64
onChange={e => dispatch(changeAddress(e.target.value))}
65
/>
66
<label htmlFor='telefono'>Teléfono</label>
67
<input
68
type='text'
69
id='telefono'
70
onChange={e => dispatch(changePhone(e.target.value))}
71
/>
72
<button
73
type='submit'
74
onClickC={handleSubmit}
75
>
76
Guardar Información
77
</button>
78
</form>
79
<button
80
type='button'
81
onClick={(e) => setEdit(false)}
82
>
83
Cancelar
84
</button>
85
</>
86
)
87
}else if(edit === false) {
88
return(
89
<>
90
<NavBar />
91
<form>
92
<label htmlFor='nombre'>Nombre</label>
93
<p
94
id='nombre'
95
>
96
{nombre}
97
</p>
98
<label htmlFor='correo'>Correo</label>
99
<p
100
id='correo'
101
>
102
{correo}
103
</p>
104
<label htmlFor='cedula'>Cédula</label>
105
<p
106
id='cedula'
107
>
108
{cedula}
109
</p>
110
<label htmlFor='direccion'>Dirección</label>
111
<p
112
id='direccion'
113
>
114
{direccion}
115
</p>
116
<label htmlFor='telefono'>Teléfono</label>
117
<p
118
id='telefono'
119
>
120
{telefono}
121
</p>
122
</form>
123
<button
124
type='button'
125
onClick={() => setEdit(true)}
126
>
127
Editar
128
</button>
129
</>
130
)
131
}
132
}
133
User model in the backend:
JavaScript
1
61
61
1
const { model, models, Schema } = require('mongoose')
2
const bcrypt = require('bcrypt')
3
4
const userSchema = new Schema({
5
email: {
6
type: String,
7
required: true,
8
validate: {
9
async validator(email) {
10
try {
11
const user = await models.User.findOne({ email })
12
return !user
13
} catch(error){
14
return false
15
}
16
},
17
message: 'El correo ya está en uso'
18
},
19
},
20
password: {
21
type: String,
22
required: true,
23
},
24
address: {
25
type: String,
26
},
27
phone: {
28
type: String,
29
},
30
products: {
31
type: [{
32
type: Schema.Types.ObjectId,
33
ref: 'Product'
34
}]
35
},
36
name: {
37
type: String,
38
required: true,
39
},
40
nationalid: {
41
type: String,
42
unique: true,
43
},
44
transactions: {
45
type: [{
46
type: Schema.Types.ObjectId,
47
ref: 'Transaction',
48
}]
49
},
50
})
51
52
userSchema.pre('save', async function() {
53
if(this.password && this.isModified('password')) {
54
this.password = await bcrypt.hash(this.password, 8)
55
}
56
})
57
58
const User = model('User', userSchema)
59
60
module.exports = User
61
Update controller in the backend:
JavaScript
1
16
16
1
async update(req, res) {
2
try {
3
const {body, params: {userId}} = req
4
5
const user = await User.findByIdAndUpdate(userId, body, {new:true}).select('-password')
6
await user.save({ validateBeforeSave: false })
7
8
res.status(201).json(user)
9
console.log(user)
10
}catch(error) {
11
res.status(400).json(`No se puede actualizar el usuario ${error}`)
12
console.log(error)
13
}
14
15
},
16
Address
and phone number
are updating correctly, however, nationalid
will not update for the life of me.
Advertisement
Answer
I found the error in my code, I forgot to change line #8 in the frontend file from const { natId, address, phone, error }
to const { nationalid, address, phone, error }
to match the name in the backend model.