You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

静态方法内执行MongoDB查询导致程序无限等待问题排查

问题:Mongoose静态方法中this指向错误导致无限等待

我跟着教程开发登录与授权系统,当前卡在Schema静态方法调用数据库操作的环节:

  • 在静态方法内调用this.findOne({})时程序进入无限等待,控制台仅输出"Static Method Triggered",后续代码无法执行
  • 移除查询语句后,程序又会在this.create行无限等待,console.log(this)返回空对象{}
  • 其他数据库查询功能正常

模型代码如下:

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

const userSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true,
    },
    password: {
        type: String,
        required: true
    }
})
userSchema.statics.signup = async (email, password) => {
    console.log("Static Method Triggered")
    const exists = await this.findOne({ email })
    console.log("Verifying existence")

    if (exists) {
        throw Error("Email is already in use")
    }
    console.log("Existence verified")

    const salt = await bcrypt.genSalt(5)
    const hash = await bcrypt.hash(password, salt)
    console.log(hash)
    const user = await this.create({ email: email, password: hash })
    console.log("End of function")
    return user
}

module.exports = mongoose.model('User', userSchema) 

原因分析

问题核心是箭头函数的this绑定规则:Mongoose的静态方法需要this指向模型本身,但箭头函数不会绑定自己的this,它会继承外层作用域的this(此处为空对象)。所以调用this.findOne、this.create时,实际上是在空对象上调用不存在的方法,导致await永远无法得到结果,进入无限等待。

解决方案

将静态方法的箭头函数改为普通函数,让this正确绑定到User模型:

userSchema.statics.signup = async function(email, password) {
    console.log("Static Method Triggered")
    const exists = await this.findOne({ email })
    console.log("Verifying existence")

    if (exists) {
        throw Error("Email is already in use")
    }
    console.log("Existence verified")

    const salt = await bcrypt.genSalt(5)
    const hash = await bcrypt.hash(password, salt)
    console.log(hash)
    const user = await this.create({ email: email, password: hash })
    console.log("End of function")
    return user
}

内容的提问来源于stack exchange,提问作者hamza malik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:52:55