Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

318
Vistas
How to update the current session when updating an array with mongoose push. Using express handlebars mongoose and node.js

I am currently trying to create a social media app, where you can only see posts of your friends and direct message only with friends. Unfortunately when adding a friend by updating the database with mongoose by pushing an item into a friends array (which works perfectly). when i then visit posts or messages, the friends has not been updated and requires logging out and then logging in again, which updates it to work exactly how I envisioned. Is this something to do with the way that the friends array is being updated?

The friends update array:

const User = require("../models/user");

const FriendsController = {
  Update: (req, res) => {
    const requesterUserID = req.session.user._id
    const receiverUserID = req.params.userID

    User.findOne({ _id: receiverUserID }).then((user) => {
      user.friends.push(requesterUserID);
      user.save(() => {
        User.findOne({ _id: requesterUserID}).then(user2 => {
          user2.friends.push(receiverUserID)
          user2.save(() => {
            res.redirect(`/profile/${receiverUserID}`);
          });
        })
      });
    });
  }
};

module.exports = FriendsController;

I cannot for the life of me figure out what is going on. I am assuming it is related to the session given the fact that it works upon refreshing the session by logging out and logging in again.

The session controller:

const User = require("../models/user");
const bcrypt = require("bcryptjs");

const SessionsController = {
  New: (req, res) => {
    res.render("sessions/new", {});
  },

  Create: (req, res) => {
    const email = req.body.email;
    const password = req.body.password;
    User.findOne({ email: email }).then((user) => {
      if (user) {
        bcrypt.compare(password, user.password).then((result) => {
          if (result) {
            req.session.user = user;
            res.redirect("/posts");
          } else {
            res.render("sessions/new", { signInError: true });
          }
        });
      } else {
        res.render("sessions/new", { signInError: true });
      }
    });
  },

  Destroy: (req, res) => {
    console.log("logging out");
    if (req.session.user && req.cookies.user_sid) {
      res.clearCookie("user_sid");
    }
    res.redirect("/sessions/new");
  },
};

module.exports = SessionsController;

clearing cookie upon logging out:

app.use((req, res, next) => {
  if (req.cookies.user_sid && !req.session.user) {
    res.clearCookie("user_sid");
  }
  next();
});

Thanks in advance for the help

over 4 years ago · Santiago Trujillo
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda