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