将带有bson-objectid的用户插入MongoDB集合时发生类型错误

qv7cva1a  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(150)

我在尝试使用insertOne方法将用户对象插入MongoDB集合时遇到了类型错误。该错误似乎与User对象的_id属性与MongoDB驱动程序中的预期类型之间的兼容性有关。
我在我的项目中使用TypeScript,并使用bson-objectid库中ObjectId类型的_id属性定义了一个User接口。库中ObjectId的类型定义被正确导入,并在整个代码库中一致使用。
但是,当我尝试使用以下代码插入用户时:

import { ObjectId } from 'bson-objectid';

export interface User {
  _id: ObjectId;
  // Other properties of User
}

// ... other code ...

await db.collection('users').insertOne(user);

字符串
我遇到以下类型错误:

./pages/api/auth/registerEmail.ts:37:41
Type error: Argument of type 'User' is not assignable to parameter of type 'OptionalId<Document>'.
  Type 'User' is not assignable to type '{ _id?: ObjectId; }'.
    Types of property '_id' are incompatible.
      Type 'ObjectID' is not assignable to type 'ObjectId'.

  35 |          verificationToken,
  36 |  }
> 37 |  await db.collection('users').insertOne(user)
     |                                         ^
  38 |  const gender = await setUserGender(db, user)
  39 |  const payload = new JwtPayload(user)
  40 |  if (!process.env.JWT_SECRET) {

> Build error occurred

    await db.collection('users').insertOne(user)


我已经确认我在整个代码库中始终使用ObjectId类型,并且我正在从bson-objectid导入它,如上所示。MongoDB驱动程序中预期的_id类型似乎与bson-objectid中的类型相同,所以我不确定为什么会发生这种类型不匹配。
我还确保使用npm正确安装了bson-objectid库。
有没有人可以帮助我了解是什么可能导致这种类型的错误,我可以如何解决它?任何见解或建议,将不胜感激。

nr9pn0ug

nr9pn0ug1#

看起来在沿着的某个地方,bson库更改了其ObjectId类型的定义。重要的是,您需要做的是将库更新到最新版本。例如,Mongodb使用bson库,因此使用mongodb的最新“^6.2.0”对我来说很有效。

相关问题