如何使用passport-local-mongoose将多个对象保存到数据库?

5
我想使用passport-local-mongoose Node.js包将用户注册到我的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函数手动设置新值,但出于某种原因,我在数据库中没有看到它们。此外,我已经将名字和姓氏包含在User模型模式中,这是模式:

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

有什么建议吗?

1个回答

3
我找到了答案,你需要在用户名字段对象中指定模式的其他值:
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
})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接