对于我的Node项目,我使用mongoose来存储/访问用户模型。在我的index.js文件中,我初始化了所有内容:
const restify = require('restify')
const Router = require('./lib/routing/Router.js')
const server = restify.createServer()
server.use(restify.plugins.bodyParser())
// init global variable
global.one = {}
// init database
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/oneboard1')
mongoose.set('debug', true)
mongoose.connection.on('error', function(err) {
console.error('MongoDB error: %s', err);
});
// init ORM
const models = require('./models.js')
one.model = models
// init middleware
const ClassAuthMiddleware = require('./middleware/AuthMiddleware')
const authMiddleware = new ClassAuthMiddleware()
// register routes
const rtr = new Router(server)
rtr.get('/user/profile', 'AuthController.getProfile').middleware('pre', authMiddleware)
rtr.post('/user/create', 'AuthController.createUser')
rtr.post('/user/auth', 'AuthController.issueToken')
rtr.bind()
server.listen(8080, function(){
console.log('%s listening at %s', "OneBoard Server", server.url)
})
// a sanity check
one.model.User.findById('5b0b256b044e0e0274b4367c')
.then(user => console.log(user))
.catch(error => console.log(error))
我的models.js文件:
const mongoose = require('mongoose')
module.exports = {
User: mongoose.model('User', {
email: {
type: String,
unique: true,
},
password: String,
clips: { type: [], default: [] },
created: { type: Date, default: Date.now },
updated: { type: Date, default: Date.now },
}),
}
验证和创建用户的路线完美运行。此外,运行User.findById在index.js文件中完美运行并返回用户对象。但是,我写了一些Auth中间件。在这个商品中,我尝试使用index.js健全性检查中的相同ID来查询User模型。但是,这一次,findById函数只是不执行!我已经打开了mongoose调试,并且在执行findById函数时它没有运行任何命令,尽管它在测试时显示为User对象中的一个函数。这是中间件文件:
const Middleware = require('../lib/routing/Middleware')
const jwt = require('jsonwebtoken')
const authHelper = require('auth-header')
const config = require('../config.js')
class AuthMiddleware extends Middleware {
exec( req, res, breakChain, next ){
const auth = authHelper.parse(req.header('authorization'))
jwt.verify( auth.token, config.auth.jwtSecret, ( error, decoded ) => {
console.log(decoded) // works
console.log({_id: decoded.id}) // works
console.log(one.model.User.findById) //works
one.model.User.findById(decoded.id) // does nothing
.then(user => console.log(user)) // doesn't execute
.catch(error => console.log(error)) // doesn't execute
console.log('post MW') // works
})
}
}
module.exports = AuthMiddleware
我一直在尝试调试这几个小时,我确信这很简单,但对于我的生活,我无法弄清楚为什么mongoose不会运行findById查询。 (为了记录,我已经检查了集合的名称与模型的名称一致。)