User.find () возвращает пустой ответ в mongodb express - PullRequest
0 голосов
/ 09 октября 2019

Я работаю со nextjs и express. Я реализую простую форму входа. Я отправляю учетные данные пользователя и использую find (), проверяя, существует ли пользователь или нет. Но find () возвращает пустой ответ. В терминале find () возвращает массив этой записи.

модель

const mongoose = require('mongoose')
const schema = mongoose.Schema

const user = new schema({
    username: { type: String} ,
    password: { type: String},
    role: { type: String},
})

module.exports = mongoose.model('user', user);

router.js

const express = require('express')
const router = express.Router()

const user = require('../models/user');
router.post('/user/signin', (req, res) => {
    user.find({
        username: req.body.username, password: req.body.password
    }, (err, user) => {
        console.log(user);
        if (err) {
            result.status(404).send({ error: 'There is some error' });
        } else if (user.length == 1) {
            var token = 'kkl';//token
            res.send({ token });
        } else {
            console.log(err);
            res.send('Incorrect Email and Password');
        }
    });
})
module.exports = router;

this.is мой index.js

const express = require('express')
const next = require('next')
const bodyParser = require('body-parser')
const PORT = process.env.PORT || 4000
const dev = process.env.NODE_DEV !== 'production' //true false
const nextApp = next({ dev })
const handle = nextApp.getRequestHandler() //part of next config
const mongoose = require('mongoose')
const router = express.Router();

nextApp.prepare().then(() => {
    const app = express();
    const db = mongoose.connect('mongodb://localhost:27017/knowledgeBase')
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use('/knowledgeBase', require('./routes/router'));
    app.get('*', (req, res) => {
        return handle(req, res) // for all the react stuff
    })
    app.listen(PORT, err => {
        if (err) {
            console.log(err);
            throw err;
        }
        console.log(`ready at http://localhost:${PORT}`)
    })
})

, пожалуйста, помогите

1 Ответ

1 голос
/ 09 октября 2019

Какой ответ вы получите, когда попробуете это? В соответствии с ответом я отредактирую ответ.

router.post("/user/signin", async (req, res) => {
  if (!req.body.username) return res.status(400).send("username cannot be null");

  if (!req.body.password) return res.status(400).send("Password  cannot be null");

  const user = await User.findOne({ username: req.body.username});

  if (!user) return res.status(400).send("User not found");

  if (req.body.password!== user.password)
    return res.status(400).send("Invalid password.");

  res.send("logined");
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...