【问题标题】:Cast to ObjectId failed for value error in Mongoose findOne由于 Mongoose findOne 中的值错误,转换为 ObjectId 失败
【发布时间】:2018-03-04 16:50:32
【问题描述】:

我一直在与一个奇怪的异常作斗争,一个小时后仍然对此感到困惑。

CastError:值“pedrammarandi@gmail.com”的对象 ID 转换失败 模型“帐户”的路径“_id”

我正在尝试通过电子邮件地址检索帐户。这是我的查询

export async function getPendingRecipients(user_id, email_address) {
    const account = await Account
        .find({email: email_address})
        .exec();

    return true;
}

这是我的架构对象

const userGmailSchema = new Schema({
    id: {
        type: String,
        unique: true
    },
    displayName: String,
    image: Object,
    accessToken: String,
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    refreshToken: {
        type: String,
        default: null
    },
    email: {
        type: String,
        unique: true
    },
    emails: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Emails'
        }
    ]
});

【问题讨论】:

    标签: javascript mongodb express mongoose ecmascript-6


    【解决方案1】:

    我不确定,但我想问题是你写了一个id 字段。

    在MongoDB中,“主键”是_id字段,它是一个ObjectId对象(实际上是一个12字节的值),而在mongoose中,id_id的一个虚拟getter ,简单地说,id_id 的别名。

    (有点不同的是,_id 返回ObjectIdid 返回String 版本的_id。)

    默认情况下,mongoose 会自动管理 _id 字段,所以我们通常不应该在 schema 中写任何关于 id 的内容。

    如果您的 id 用于 SQL DB 中的主键 ID 之类的东西,只需将其从猫鼬模式中删除即可。如果它在您的应用中有其他含义,请尝试添加一个选项:

    const userGmailSchema = new Schema({
        // your schemas here
    }, 
    {
        { id: false }  // disable the virtual getter
    })
    

    或重命名。

    http://mongoosejs.com/docs/guide.html#id

    希望这会有所帮助。

    【讨论】:

    • 谢谢,这是一个非常重要的信息,没有这个我特别卡住,因为我们所有的 id 都是自定义生成的数字而不是对象 id。因此,如果 id 是其他任何东西,那么 ObjectId 设置这个属性就变得非常重要。
    猜你喜欢
    • 2020-12-16
    • 2022-08-15
    • 2013-03-24
    • 2021-09-05
    • 2021-03-09
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 2018-09-13
    相关资源
    最近更新 更多