首页 > 解决方案 > 在 node.js 中为注册用户创建配置文件

问题描述

我有一个存储在 MongoDB 中的用户模型,我希望为注册到我网站的每个用户创建一个唯一的用户配置文件。

这是用户模型:

var UserSchema = mongoose.Schema({
    username: {
        type: String,
        index:true,
        unique: true
    },
    password: {
        type: String
    },
    email: {
        type: String,
        unique: true
    },
    name: {
        type: String
    },
    avatar: {
        type: String
    }
});

尝试从我观看的视频中执行类似以下代码的操作,但它根本不起作用:

router.get("/:username", function(req,res){
    User.findOne({where: {username: req.params.username}}, function(err,foundUser){
        if(err){
            req.flash("error", "Something went wrong.");
            return res.redirect("/");
        }
        res.render('profile',{user:foundUser});
    })
});

而“/:username”必须是用户的用户名。

如何在他注册后创建用户资料,并让其他用户看到?

提前致谢!

标签: javascripthtmlnode.jsmongodb

解决方案


我认为您的处理程序应该是:

router.get("/:username", function(req,res){
    User.findOne({username: req.params.username}, function(err,foundUser){
        if(err){
            req.flash("error", "Something went wrong.");
            return res.redirect("/");
        }
        res.render('profile',{user:foundUser});
    })
});

推荐阅读