"mongoose": "^5.12.2"
I have a schema named User. This schema has a field named "rol" of type string[] for a multiple rol application (User, Admin, Freetour, BarOwner, etc).
The function that adds a rol to a user is defined like this:
public addRolToUser = (idUser:string, newRol:string):Promise<IUser> => {
try{
return new Promise<IUser>((resolve, reject) => {
User.findByIdAndUpdate(idUser, { addToSet: {rol:newRol} }, {new:true}).then(user => {
return resolve(user);
}).catch(err => {
return reject(err);
});
});
}catch (e) {
throw e;
}
};
However this doesn´t update the "rol" field of the user. The following function should add the rol "FreeTour" to the user with the id returned by "petition.user".
public acceptPetition = async(req:Request, res:Response) => {
try{
return this.solFreeTourService.acceptPetition(req.body.idPetition).then(petition => {
let acceptPromise = new Promise((resolve, reject) => {
// Here I´m invoking the addRolToUser function
return this.userService.addRolToUser(petition.user, "FREETOUR").then((resUser)=>{
// resUser here has the same value for the "rol" field, didn´t get updated.
return resolve(petition);
}).catch(err=>{
return reject(err);
})
})
return acceptPromise.then(petition=>{
return res.status(200).json({petition});
}).catch(e=>{
res.status(400).json({ status: 400, message: "There has been an error." });
});
})
}catch (e) {
res.status(400).json({ status: 400, message: "There has been an error." });
}
}
I don't want repeated values in the "rol" array, hence pushing is not an option.
What am I doing wrong?