[在创建帖子(尝试-sessions,猫鼬)时尝试刷新用户时出现Cast to ObjectId错误]] << [

问题描述 投票:2回答:2
[当用户登录到应用程序时,我正在使用Express-Sessions进行验证,我将一个user_id附加到sessions对象,我将在创建帖子时使用它,以尊重创建该帖子的用户,最终我希望让用户在馆藏内创建所有这些帖子,以便我可以轻松地在用户仪表板上显示它。


您可以通过我的github重新创建错误:https://github.com/fullstackaccount/auth_cookies-Session,使用邮递员信息:创建用户,登录,然后尝试提交帖子。邮递员文件:https://documenter.getpostman.com/view/8427997/SWEB1amP?version=latest

我正在尝试使用此解决方案来创建对帖子的引用:https://teamtreehouse.com/community/how-to-assign-a-user-a-post-with-mongoose-and-express

谢谢您的时间!


这是登录名:

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'); } });

这是发布路线,此处可以使用express-sessions,我试图用其ID保存用户,但出现错误:

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}`); }); }); }); }); });

根据请求,职位和用户模型:

POST模式:

{ title: { type: String, default: 'BreakfastQueenROCKS' }, content: { type: String, default: 'Booyeah!' }, author: [ { type: mongoose.Schema.Types.ObjectId, ref: 'User' } ] }, { timestamps: true } );

用户型号:

{ 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 } );

[当用户登录到应用程序时,我正在使用Express-Sessions进行验证,我将一个user_id附加到sessions对象上,这将在我创建帖子时使用,以尊重创建该用户的用户...
node.js mongodb express mongoose express-session
2个回答
1
投票
我相信问题与将帖子推到User模型有关。您拥有的是user.posts.push(newPost);,它是整个发布对象,但是用户模型将发布定义为:

0
投票
解决方案,以防有人需要:
© www.soinside.com 2019 - 2024. All rights reserved.