【问题标题】:how to save multiple objects to database with passport-local-mongoose?如何使用护照本地猫鼬将多个对象保存到数据库?
【发布时间】:2021-03-21 07:47:36
【问题描述】:

我想使用 passport-local-mongoose 节点包将用户注册到我的 mongoDB 数据库,我对此没有任何问题,但我想要向数据库添加的不仅仅是用户名和密码:例如(他们的名字和姓氏,他们的角色以及用户所需的几乎所有内容)

如何使用 passport-local-mongoose 来做到这一点,或者除了使用该软件包之外还有其他方法吗,我已经尝试将其他对象添加到数据库中,但由于某种原因它不起作用。这是我试图将额外的对象放入数据库的方法:

app.post('/register', function(req, res){
    User.register({username: req.body.username}, req.body.password, function(err, user) {
        if (err) { 
            console.log(err);
            res.redirect('/register')
         } else{
            passport.authenticate('local')(req, res, function(){
                User.updateOne({ username: req.body.username }, { $set: { firstName: 'firstnName', lastName: 'lastName' } })
                res.redirect('/secrets')
            })
           };
      });
})

如您所见,我使用 mongoose 的 updateOne 函数手动设置新值,但由于某种原因,我在数据库中看不到它们。而且我在用户模型架构中包含了名字和姓氏,这是架构:

const userSchema = new mongoose.Schema ({
    email: String,
    password: String,
    firstName: String,
    lastName: String
})

有什么建议吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose passport-local-mongoose


    【解决方案1】:

    我找到了答案,您必须使用用户名字段对象指定架构的其他值:

    app.post('/register', function(req, res){
        User.register({username: req.body.username, firstName: req.body.firstName, lastName: 
            req.body.lastName}, req.body.password, function(err, user) {
            if (err) { 
                console.log(err);
                res.redirect('/register')
             } else{
                passport.authenticate('local')(req, res, function(){
                    res.redirect('/secrets')
               };
          });
    })
    

    您应该将架构更改为:

    const userSchema = new mongoose.Schema ({
        username: String,
        password: String,
        firstName: String,
        lastName: String
    })
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-25
      • 2017-06-09
      • 2019-10-05
      • 2018-07-31
      • 2021-10-24
      • 1970-01-01
      • 2017-04-02
      • 2016-10-19
      相关资源
      最近更新 更多