DEV Community

Sumit Chahar
Sumit Chahar

Posted on

Storing the user data in our database

Now that we have handled our routes and also written the strategy for OAuth in the previous article. We will now save the user information to our database.

Note: We are using mongoDB and mongoose for our application.

We will create a models folder in our project folder and create a User.js file in which will be our User model and we will write the user schema in this file.

The User.js file will look like this -

Image description

Now we will connect our local database with our application we will need to import mongoose connect it using mongoose.connect middleware

mongoose.connect("mongodb://localhost/sampleLogin", err => {
  console.log(err ? err : "Database connected successfully");
});
Enter fullscreen mode Exit fullscreen mode

We also need to add a store to our session using instance of MongoStore in which we will pass the url of our local database.

app.use(
  session({
    secret: process.env.SECRET,
    saveUninitialized: false,
    resave: false,
    store: new MongoStore({ mongoUrl: "mongodb://localhost/sampleLogin" })
  })
);
Enter fullscreen mode Exit fullscreen mode

The app.js file will appear like this now -

Image description

We've also added passport.session() middleware in app.js which can give us information about the current logged in user in the session.

At last we should also import our User model in the passport.js file. To create new user.

Now by default passport uses serializeUser method to persist user data in the session. We'll use it in the next article to persist user information.

Go to next article 👉

Top comments (0)