I'm using node with typescript, and mongoose for database.
I have this code that takes user model from database (using mongoose) by user id, then takes the user roles attribute. The roles attribute contains array of object. Inside each object (roles) contains _id
// Check User Roles
const user = await this.userModel.findById(req.identitas.user._id)
const userRoles: Array<string> = []
for (let index in user.roles) {
userRoles.push((user.roles[index]._id))
}
When i try to check the type of what's pushed to userRoles
console.log(typeof(userRoles[0]))
It says that it has object
type variable.
I then decided to try
userRoles.push({ dummy: "dummy" })
and it wouldn't let me do that. So I know for sure that the type declaration in
const userRoles: Array<sring> = []
is working properly. But, at the same time, it isn't. When I try to push _id to userRoles, it still somehow allows me to do that.
This is a problem because I'm using this userRoles array of string to compare it with another string value, using
userRoles.includes("some-string-here")
Why and how did this thing could happen?
*This is what user
variable contains:
{
roles: [
{
_id: 5f93fdc**********36,
name: 'Karyawan Cabang Neutron',
...
__v: 2,
policies: [],
organization: 5f8fe9a62*****000082e3fef
}
],
units: [
{
_id: 5fc1f9******00081b2897,
name: 'Neutron Yogyakarta 2',
code: '102',
organization: 5f8fe****42a2000kj13fef,
createdAt: 2020-11-28T07:18:09.628Z,
updatedAt: 2020-11-28T07:18:09.628Z,
__v: 0
}
],
organizations: [
{
_id: 5f8c6b*****b75jg008d4a156,
...
__v: 34,
code: 'NEO',
logo: [Object],
content: [Array],
object: [Object],
config: [Array]
}
],
_id: 5fdad1a25e9f78****c42,
email: 'email@example.com',
username: 'EmiliaBestGirl',
...
isEmailVerified: true,
identities: [],
createdAt: 2020-12-17T03:33:54.484Z,
updatedAt: 2020-12-22T08:12:24.019Z,
__v: 3,
...
}