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

使用lucia-auth与MongoDB实现登录功能时遇类型错误求助

Lucia-Auth 登录代码报错:Property 'password' does not exist on type 'Query<any[], any, {}, any, "find">'

错误原因

你的route.ts里存在两个核心问题:

  1. 未等待异步查询结果:User.find({username})返回的是Mongoose的Query对象,不是实际的用户数据,必须通过await执行查询才能拿到结果。
  2. 使用了错误的查询方法:find()返回的是匹配用户的数组,而你需要单个用户,应该用findOne()方法。

这两个问题导致existingUser是Query类型(而非用户文档),所以TypeScript会提示password属性不存在,同时if (!existingUser)的判断永远不会成立(因为Query对象始终为真值)。

修复方案

修改route.ts中的用户查询逻辑,具体改动如下:

// 替换原有的查询及后续代码
try {
    const existingUser = await User.findOne({ username });
    if (!existingUser) {
        return {
            error: "Incorrect username or password"
        };
    }

    const validPassword = await new Argon2id().verify(existingUser.password, password);
    if (!validPassword) {
        return {
            error: "Incorrect username or password"
        };
    }

    // 注意:你的用户模型用_id作为主键,需转成字符串传入
    const session = await lucia.createSession(existingUser._id.toString(), {});
    const sessionCookie = lucia.createSessionCookie(session.id);
    cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
    return redirect("/");
} catch (error) {
    // 捕获数据库查询异常
    return {
        error: "An error occurred during login"
    };
}

额外说明:

  • 你的用户模型定义中使用_id作为主键,而非Lucia默认的id,所以创建Session时需要把_id转为字符串传入
  • 增加try/catch块可以处理数据库查询时可能出现的异常,避免程序直接崩溃

内容的提问来源于stack exchange,提问作者gill bates

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:47:36