在创建 post 时尝试引用用户时出现 Cast to ObjectId 错误(express -sessions,mongoose)

Getting a Cast to ObjectId error when trying to refrence users when creating post (express -sessions, mongoose)

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


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

我正在尝试使用此解决方案来创建对 posts 的引用: 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 路线,这里可以使用 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 路线:


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 和用户模型:

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

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

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

所以看起来你只想存储用户的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}`);
        });
    });
});

已修复解决方案以备不时之需:

post 型号

router.post('/', (req, res, next) => {

                // We need to find the logged in user, it is passed in the sessions object from userModel when /login is hit
            userModel.findById(req.session.user_id, (error, user) => {

            // 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_id:  mongoose.Types.ObjectId(req.session.user_id)
            };

            // we create our new post in our database
        postModel.create(newPost, (error, returnedDocuments) => {
            if (error){
            res.redirect('/');
            throw new Error(error);

            }


                // we insert our newpost in our posts field corresponding to the user we found in our database call
                user.posts.push(returnedDocuments._id);
                // we save our user with our new data (our new post).
                user.save((err) => {
                    return res.redirect(`${returnedDocuments._id}`);
                });
    });


            // this will populate the posts field in our userSchema (which contain the id references to our posts)
            userModel.findById(req.session.user_id).populate('posts').exec((err, user) => {
                console.log('user.posts======',user.posts);
            });
        });
});

登录码:

// User can Login for their account
router.post('/login', (req, res, next) => {
    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');
    }
});