以下代码引发以下错误:
await this.GuildModel.findOne({ _id: guildId }).exec((guild) => {
console.log(guild);
});
CastError: Cast to ObjectId failed for value "894673322397302784" (type string) at path "_id" for model "GUILD"
{
messageFormat: undefined,
stringValue: '"894673322397302784"',
kind: 'ObjectId',
value: '894673322397302784',
path: '_id',
reason: BSONTypeError: Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer
我的架构和数据库中的 _id value 是字符串类型,因此我不希望它被转换为 ObjectID,我的架构:
const GuildSchema = {
_id: { type: String },
prefix: { type: String, default: "!" },
}
在做了一些研究之后,我意识到我不能使用 findById,因为它强制它使用 ObjectID,这就是我使用 findOne 的原因。我将如何通过字符串类型的 _id 进行查询。
回答1
_id 为我的 MongoDB 的 ObjectID 保留,使用 id(不是 _id)作为您自己生成的 ID,并且在您的查询中也使用 id,您应该没问题。