0

UPDATE:

I somehow believe the problem comes from the backend. In the user.findbyIdAndUpdate funtion, inside the callback, the variable user(or result) is returning the previous information, despite the new one is shown in the database (I'm cheking it with Robo 3t). So I don't know what exactly is happening here.

I am uploading a picture as avatar to a nodejs-mongo server. It seems to work when the project is compiled the first time, but after I try to change the picture a second time, it works this way:

Upload picture2 and picture 2 expectedly shows.

Upload picture3 and picture2 is stays. (picture3 should show).

Upload picture4 and picture3 is loaded. (picture4 should show).

it keeps this way, showing on screen the previously uploaded picture.

I have tried with ngZone and observables as it is explained here, but the behaviour is the same.

My code:

profile.components.ts

user: any;
userupdater = new BehaviorSubject < string > (this.user);
file2Base64result;
//CODE
async file2Base64(archivo) {
    const file = archivo.target.files[0];
    this.file2Base64result = "";
    this.file2Base64result = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });

    let user: UserI = {
        id: 0,
        name: "",
        password: "",
        email: "",
        avatar: this.file2Base64result
    };
    this.authService.updateAvatar(user).subscribe(
        res => {

        },
        err => {},
        () => {
            this.user = JSON.parse(localStorage.getItem("currentUser")); //I believe the problem could be here
            this.userupdater.next(this.user);
            Swal.close();
        })
}

Relevant part of profile.component.html <img class="avatarimage" src="{{ user.avatar }}" />

auth.service.ts


updateAvatar(user: UserI): Observable < JwtResponseI > {
    let currentu = < UserI > JSON.parse(localStorage.getItem("currentUser"));
    /* console.log("currentu: "+JSON.stringify(currentu)); */
    if (user.avatar) currentu.avatar = user.avatar;
    return this.httpClient.post < JwtResponseI > (`${this.AUTH_SERVER}/updateavatar`,
        currentu).pipe(tap(
        (res: JwtResponseI) => {
            if (res) {
                let currentU = {
                    name: res.dataUser.name,
                    email: res.dataUser.email,
                    role: res.dataUser.role,
                    id: res.dataUser.id,
                    avatar: res.dataUser.avatar,
                    signature: res.dataUser.signature
                };
                //guardar token
                this.saveToken(res.dataUser.accessToken, res.dataUser.expiresIn, currentU);
            }
        }, error => {
            console.log(error);
        },
        () => {}
    ));
}

private saveToken(token:string, expiresIn:string, CurrentUser):void{

  this.isLoggedIn = this.token;
  const expiresAt = moment().add(localStorage.getItem('EXPIRES_IN'),'second');
  localStorage.removeItem("ACCESS_TOKEN");
  localStorage.removeItem("EXPIRES_IN");
  localStorage.removeItem("currentUser");
  localStorage.setItem("ACCESS_TOKEN", token);
  localStorage.setItem("EXPIRES_IN", JSON.stringify(expiresAt.valueOf()));
  this.token = token;
  this.expiresin = JSON.stringify(expiresAt.valueOf());
  localStorage.setItem("currentUser", JSON.stringify(CurrentUser));

  this.token = token;
}

In backend, the relevant code:

exports.updateavatar = (req, res, next) => {
    /* console.log("request:xxxxxxxxxx "+JSON.stringify(req.body)); */
    console.log("request:id " + JSON.stringify(req.body.id));

    var ObjectId = require('mongoose').Types.ObjectId;
    var elementid = new ObjectId(req.body.id);

    User.findByIdAndUpdate({
        _id: elementid
    }, {
        $set: req.body
    }, (err, user) => {
        if (err) {
            console.log("Error en findByIdandUpdate: " + err);
            return res.status(500).send('No se encuentra el usuario.');
        }
        if (!user) {
            res.status(409).send({
                message: 'Esta ID de usuario no existe.'
            });
        } else {
            const expiresIn = 14 * 60 * 60;
            const accessToken = jwt.sign({
                    id: user.id
                },
                SECRET_KEY, {
                    expiresIn: expiresIn
                });
            const dataUser = {
                id: user.id,
                name: user.name,
                email: user.email,
                accessToken: accessToken,
                expiresIn: expiresIn,
                role: user.role,
                avatar: user.avatar,
                signature: user.signature
            }
            res.send({
                dataUser
            });
        }
    });
}

exports.createUser = (req, res, next) => {
    console.log("request:xxxxxxxxxx " + JSON.stringify(req.body));
    const newUser = {
        name: req.body.name,
        email: req.body.email,
        password: bcrypt.hashSync(req.body.password),
        role: req.body.role,
        avatar: req.body.avatar,
        signature: req.body.signature
    }

    User.create(newUser, (err, user) => {
        if (err && err.code === 11000) {
            return res.status(409).send("El email ya está en uso.");
        }
        if (err) {
            console.log(err);
            return res.status(500).send("No se ha podido crear el usuario");
        }
        const expiresIn = 14 * 60 * 60;
        const accessToken = jwt.sign({
                id: user.id
            },
            SECRET_KEY, {
                expiresIn: expiresIn
            });
        const dataUser = {
            id: user.id,
            name: user.name,
            email: user.email,
            accessToken: accessToken,
            expiresIn: expiresIn,
            role: user.role,
            avatar: user.avatar,
            signature: user.signature
        }
        //response
        res.send({
            dataUser
        })
    })
}

Germán
  • 1,007
  • 1
  • 7
  • 20

1 Answers1

0

The mongo function findbyIdandupdated needs a parameter like {new:true} so it returns the updated object. Otherwise returns the previous one.

Germán
  • 1,007
  • 1
  • 7
  • 20