我在user.js文件中定义了我的猫鼬模式。
//user.js
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
let userSchema = new mongoose.Schema({
email: {
type:String,
require:true,
trim:true,
minlength: 1,
unique:true,
validate:{
validator: validator.isEmail
,
message: '{value} is not valid',
}
},
password:{
type:String,
required:true,
minlength:6
},
tokens: [{
access:{
type:String,
required:true
},
token:{
type:String,
required:true
}
}]
})
userSchema.statics.findByToken = function(token){
console.log('token');
let User = this;
console.log("this is: ",User);
let decoded;
try{
decoded = jwt.verify(token,'abc123')
}catch(e){
return Promise.reject();
}
return User.findOne({
_id: decoded._id,
'tokens.token': token,
'tokens.access': 'auth'
})
}
const User = mongoose.model('User', userSchema );
module.exports = {
User: User,
}
我试图将其导入一个单独的文件中,并在app.get("users/me") route
中调用函数findByToken。该功能旨在接收令牌作为参数,并从数据库中查找与该令牌关联的文档。
代码粘贴在下面
//server.js
const express = require('express');
const {User} = require('./models/user.js');
const bodyParser = require('body-parser')
let app = express();
app.use(bodyParser.json());
process.env.port = 3000;
const PORT = process.env.port;
app.get('/users/me',(req,res)=>{
let token = req.header('x-auth')
User.findByToken(token).then((user)=>{
if(!user){
return Promise.reject();
}
res.status(200).send(req.user);
}).catch(e)=>{
res.status(401).send();
}
})
app.listen(PORT,()=>{
console.log('listening to port: ',PORT)
})
运行代码时,出现此错误。
答案 0 :(得分:0)
module.exports = User = mongoose.model('users', UserSchema);
在您的user.js中看不到导出表达式