使用MongoDB的Node中的TypeScript键入错误:OptionalId < Document>[]

c90pui9n  于 2023-10-22  发布在  TypeScript
关注(0)|答案(1)|浏览(112)

我成功地连接并写入我的MongoDB集合,但有一个类型错误,我无法弄清楚。下面的代码和错误:

interface Movie {
  id: number;
  title: string;
  createdAt?: Date;
  ...
}

...

const getCacheConn = async (): Promise<Collection<Document>> => {
  const client = await MongoClient.connect(
    `mongodb+srv://username:[email protected]/${mydb}?retryWrites=true&w=majority`
  );

  const dbConn = client.db(mydb);

  return dbConn.collection(mycache);
};

const cacheMovies = async (movies: Movie[]) => {
  ...
  const cacheConn = await getCacheConn();
  cacheConn.insertMany(movies); // IDE highlights "movies" here and shows error.
};

错误:

Argument of type 'Movie[]' is not assignable to parameter of type 'OptionalId<Document>[]'.
  Type 'Movie' is not assignable to type 'OptionalId<Document>'.
    Type 'Movie' is missing the following properties from type 'Pick<Document, keyof Document>': close, normalize, URL, alinkColor, and 246 more.

我是不是漏了什么?Promise<Collection<Document>>可能是集合的错误类型吗?我四处搜索,但找不到有关此错误的信息。

vcirk6k6

vcirk6k61#

试试这个:

interface Movie {
  id: number;
  title: string;
  createdAt?: Date;
  ...
}

...

const connectDB = async () => {
  const client = await MongoClient.connect(
    `mongodb+srv://username:[email protected]/${mydb}?retryWrites=true&w=majority`
  );

return client.db()
};

const cacheMovies = async (movies: Movie[]) => {
  ...
  const db = await connectDB();
  db.collection(mycache).insertMany(movies)
};

相关问题