Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

319
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda