2017-09-23 113 views
0

我一直在为一个奇怪的异常而苦苦挣扎,一小时后仍然对它感到困惑。强制转换为ObjectId在Mongoose中的值错误失败findOne

CastError: Cast to ObjectId failed for value "[email protected]" at path "_id" for model "Account"

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

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

    return true; 
} 

这是我的Schema对象

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' 
     } 
    ] 
}); 

回答

0

我不知道,但我想这个问题是你写的id场。

在MongoDB中,将“主键”是_id场,这是一个ObjectId对象(实际上这是一个12字节的值),并且在猫鼬,id_id虚拟吸气剂,容易表示,id是别名_id

(有一点不同的是,_id回报ObjectIdid回报String版本的_id

默认情况下,猫鼬自动管理_id领域,所以一般我们不应该写在架构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

希望这有助于。

相关问题