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

标签 node.js mongodb express mongoose express-session

当用户登录应用程序时,我使用快速 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/

相关文章:

javascript - p2p文件下载中node.js写入文件流无序

ruby-on-rails - 在 Rails 中使用 Mongoid 的 MongoDB - 地理空间索引

javascript - Express js - 数据库连接中的 Promise 待定

javascript - 无法让 globalShortcut 使用 Node/Electron javascript 应用程序中的发送函数将命令注册到 index.js

Django MongoDB SITE_ID 错误

javascript - 正确隐藏数据库凭据

node.js - Passport.js 记住我功能

javascript - 如何使用expressjs将数据保存在mongoDB上?

mysql - 获取列数据并插入到另一列中给出的 id 的行中 - sql nodejs

javascript - 调用 ng-click 后对 ng-class 没有影响