When user logs into the application, I am using express-sessions to verify them, I attach a user_id to the sessions object , this I will use when I am creating a post, to refrence the user who created that post, eventually I want to have all those post a user created , inside a collection, such that I can easily show it on users dashboard.
You can recreate the bug by my github: https://github.com/fullstackaccount/auth_cookies-Session, use the postman information to : create user,login, then try to submit post. postman Docs: https://documenter.getpostman.com/view/8427997/SWEB1amP?version=latest
I am attempting to use this solution to create this refrence to posts: https://teamtreehouse.com/community/how-to-assign-a-user-a-post-with-mongoose-and-express
THANK YOU FOR YOUR TIME!
This is the login:
console.log(req.session);
if (!req.session.user) {
/// If the user does not exist , check if they are authenticated by sessions (express sessions makes authorization in headers)
var authHeader = req.headers.authorization;
if (!authHeader) {
var err = new Error('You are not authenticated ...');
res.setHeader('WWW-Authenticate', 'Basic');
err.status = 401;
return next(err);
}
var auth = new Buffer.from(authHeader.split(' ')[1], 'base64').toString().split(':');
var username = auth[0];
var password = auth[1];
User.findOne({ username: username })
.then((user) => {
if (user === null || user.password !== password) {
// Client tried to login and username/password could not be found
var err = new Error('Username or Password could not be found');
err.status = 403; // 403 = forbidden access
next(err);
} else if (user.username === username && user.password === password) {
// double check everything is there, though it should be!
req.session.user = 'authenticated';
req.session.user_id = user._id; // the user.id is being stored in the sessions object alongside with the cookie
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('You are authenticated!');
console.log(`req.session.information ==== ${req.session.information}`);
}
})
.catch((err) => next(err));
} else {
// we passed the block of user not existing (!req.session.user), so they are auth, nothing to see here.. move along!
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('you are already authenticated my love');
}
});
This is the Post route, here the express-sessions is availiable, I attempt to save the user with their ID but I get an error :
throw er; // Unhandled 'error' event
^
MongooseError [CastError]: Cast to ObjectId failed for value "{
title: 'Myposting',
content: 'hi',
author: [ 5df8a29be1e23f2d442e8530 ]
}" at path "posts"
POST ROUTE:
router.post('/', (req, res, next) => {
console.log(`Checking to see if session is passed =================== ${req.session}`); // session object
console.log(`Checking to see if req.session.information is passed =================== ${req.session.user_id}`); // mongoDB id of user
postModel.create(req.body, (error, returnedDocuments) => {
userModel.findById(req.session.user_id, (error, user) => {
if (error) throw new Error(error);
console.log(returnedDocuments);
let myUser = mongoose.Types.ObjectId(req.session.user_id);
// We create an object containing the data from our post request
const newPost = {
title: req.body.title,
content: req.body.content,
// in the author field we add our current user id as a reference
author: [ myUser ] //ObjectID(req.session.user_id)
};
// we create our new post in our database
postModel.create(newPost, (err, post) => {
if (err) {
res.redirect('/');
throw new Error(err);
}
// we insert our newpost in our posts field corresponding to the user we found in our database call
user.posts.push(newPost);
// we save our user with our new data (our new post).
user.save((err) => {
return res.redirect(`/posts/${post.id}`);
});
});
});
});
});
As per request, post and user model :
POST MODEL :
{
title: {
type: String,
default: 'BreakfastQueenROCKS'
},
content: {
type: String,
default: 'Booyeah!'
},
author: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
]
},
{
timestamps: true
}
);
USER MODEL:
{
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: false
},
// we refrence the postModel,
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
]
},
{
timestamps: true
}
);
I believe the issue has to do with pushing the post onto the User
model. What you have is user.posts.push(newPost);
, which is the whole post object, but the user model defines posts as:
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
]
So it seems that you only want to store the post ID on the user, so you can simply change the above mentioned line to user.posts.push(newPost._id);
With the update it should should look like so:
userModel.findById(req.session.user_id, (error, user) => {
if (error) throw new Error(error);
let myUser = mongoose.Types.ObjectId(req.session.user_id);
const newPost = {
title: req.body.title,
content: req.body.content,
author: [ myUser ]
};
postModel.create(newPost, (err, post) => {
if (err) {
res.redirect('/');
throw new Error(err);
}
user.posts.push(newPost._id);
user.save((err) => {
return res.redirect(`/posts/${post._id}`);
});
});
});