gpt4 book ai didi

node.js - 创建帖子时尝试引用用户时出现转换为 ObjectId 错误(express -sessions、mongoose)

转载 作者:太空宇宙 更新时间:2023-11-03 22:04:03 24 4
gpt4 key购买 nike

当用户登录应用程序时,我使用快速 session 来验证它们,我将 user_id 附加到 session 对象,我将在创建帖子时使用它,以最终引用创建该帖子的用户我希望将用户创建的所有帖子放在一个集合中,以便我可以轻松地将其显示在用户仪表板上。

<小时/>

您可以通过我的github重新创建该错误:https://github.com/fullstackaccount/auth_cookies-Session ,使用 postman 信息:创建用户,登录,然后尝试提交帖子。 postman 文档: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');
}
});

这是 Post 路由,这里可以使用快速 session ,我尝试保存用户及其 ID,但收到错误:

      throw er; // Unhandled 'error' event
^
MongooseError [CastError]: Cast to ObjectId failed for value "{
title: 'Myposting',
content: 'hi',
author: [ 5df8a29be1e23f2d442e8530 ]
}" at path "posts"

发布路线:


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

根据请求、帖子和用户模型:

后模型:

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

最佳答案

我认为该问题与将帖子推送到 User 模型有关。您拥有的是 user.posts.push(newPost);,它是整个帖子对象,但用户模型将帖子定义为:

        posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
]

看来您只想存储用户的帖子 ID,因此您只需将上述行更改为 user.posts.push(newPost._id);

更新后,它应该看起来像这样:

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

关于node.js - 创建帖子时尝试引用用户时出现转换为 ObjectId 错误(express -sessions、mongoose),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59373896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com