【发布时间】:2020-02-06 10:41:12
【问题描述】:
我正在使用 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);
路由器.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}`)
})
})
请帮忙
【问题讨论】:
-
为什么不使用
findOne()??相反。您正在寻找一个用户对吗?。Find 会不必要地遍历所有文档,从而延长您的响应时间 -
您的代码看起来不错,您确定特定用户名的数据存在吗??可以尝试
console.log(req.body.username)看看用户名是否存在。 -
@Shubh 尝试 findOne() 返回 null
-
这清楚地表明该用户名的数据在 mongodb 中不存在
-
@Shubh 但是当我在终端尝试它的发送数组时
标签: node.js mongodb express mongoose next.js