在express中发送对象会导致一个空对象

m2xkgtsf  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(356)

这是用户路由器的登录后方法,它查找用户,生成令牌,并返回包含所述用户和令牌的对象。它还记录用户的console.log,因此我确信它已加载。

router.post("/user/login", async (request, response) => {
try{

    const user = await User.findByCredentials(request.body.email, request.body.password)
    const token = await user.generateAuthToken()
    console.log(user)
    response.json({
        user: user,
        token
    })
}catch(error){
    console.log(error)
    response.status(400).send()
}
})

这是我通过andrew mead的课程学习制作的用户模型。

const validator = require("validator")
const bcrypt = require("bcrypt")
const jwt = require("jsonwebtoken")

const Housekeeping = require("./housekeeping")

const userSchema = mongoose.Schema({
name:{
    type: String,
    required: true,
    trim: true
},
surname:{
    type: String,
    required: true,
    trim: true
},
role:{
    type: String,
    required: true
},
password: {
    type: String,
    required: true,
    validate(value){
        if(value < 6){
            throw new Error("Password must be at least 6 characters long.")
        }

        if(value.toLowerCase().includes("password")){
            throw new Error("Password can\'t contain \"password\".")
        }
    }
},
email: {
    type: String,
    unique: true,
    lowercase: true,
    validate(value){
        if(!validator.isEmail(value)){
            throw new Error("Email is invalid.")
        }
    }
},
tokens: [{
    token:{
        type: String,
        required: true
    }
}]
},{
timestamps: true
})
//Reference fields
userSchema.virtual("housekeepings", {
ref: "Housekeeping",
localField: "_id",
foreignField: "user"
})

//Custom schema methods
userSchema.methods.generateAuthToken = async function(){
const user = this

const token = jwt.sign({_id: user._id.toString()}, process.env.JWT_SECRET)
user.tokens = user.tokens.concat({token})
await user.save()

return token
}

userSchema.methods.toJSON = async function(){
const user = this
const userObject = user.toObject()

delete userObject.password
delete userObject.tokens

return userObject
}

userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({email})

if(!user){
    throw new Error("Unable to login.")
}

const isMatch = await bcrypt.compare(password, user.password)

if(!isMatch){
    throw new Error("Unable to login")
}

return user
}

//Middleware
userSchema.pre("save", async function(next){
const user = this

if(user.isModified("password")){
    user.password = await bcrypt.hash(user.password, 10)
}

next()
})

const User = mongoose.model("User", userSchema)

module.exports = User

console.log按预期显示用户对象,但另一侧的结果是空对象(“user”:{})
我用 Postman 核实

我使用以下软件:
操作系统:rhel8(红帽企业linux 8)
ide:VisualStudioCodeV1.58
node.js:v10.24.0
express:v6.14.11

qoefvg9y

qoefvg9y1#

我相信 async 关键字导致用户架构中的以下行出现问题:

userSchema.methods.toJSON = async function(){

因此,删除异步可以解决这个问题。
原因可能与github中的此问题相同。

相关问题