简体   繁体   中英

How to get a specific object in mongoose with mongoDB?

So I have this problem where I want to log-in my users with the form that I created in EJS. The problem I'm having is that after registering users I can't log them in because I don't know-how. The registration records were saved to MongoDB, so that should not be the problem Here is what I want to do:

  • Get the email address of the user from the EJS Form
  • Get the password of the user from EJS Form
  • Check if the password and email match
  • Log them in with a simple `Hello ${User.name}`` message

Here is my Folder Structure Image

routes/login.js file

// routes/login.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/user');

router.get('/', (req, res) => {
    res.render('pages/login');
});

router.post('/', (req, res, next) => {
    const email = User.find({})
    const pass = User.find({password: req.body.password});
    if (pass != req.body.password) {
        res.json({
            ERROR: "Password Is Not Correct"
        });
    }else {
        user.findOne(email)
        .exec()
        .then(doc => res.send(doc).json({
            DETAILS: "Logged in as " + `${User.name}`
        }))
        .catch(err => {console.log(err); res.send("Error")})
    }
})

module.exports = router;

models/user.js model

const mongoose = require('mongoose');
const userSchema = mongoose.Schema ({
    _id: mongoose.Schema.Types.ObjectId,
    name: String,
    email: String,
    password: String
})
module.exports = mongoose.model('Account', userSchema);

And views/partials/regform.ejs file

<form action="/login/" method="POST">
  <div class="form-group">
    <label for="email">Email address</label>
    <input type="email" required class="form-control" id="email" name="email" aria-describedby="email">
  </div>
  <div class="form-group">
    <label for="Password">Password</label>
    <input type="password" required class="form-control" name="password" id="password">
  </div>
  <input type="submit" class="btn btn-primary" value="Submit"/>
</form>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>

Thank you for taking the time to read this question.

The solution to my problem is the following.

//login.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const User = require('../models/user');

router.get('/', (req, res) => {
    res.render('pages/login');
});

router.post('/', async (req, res) => {
    let user;
    try {
      user = await User.findOne({email: req.body.email, password:req.body.password})
    } catch (e) {
      console.error(e)
    }
    if(user) {
      res.status(200).json({LOGGED_IN_AS: user});
    } else {
      res.status(404).json({error: "Some error message"});
    }
})

module.exports = router;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM