MongoDB 节点中的 TypeScript 键入错误:OptionalId<Document>[]



我成功地连接并写入了我的MongoDB集合,但有一个类型错误我无法解决。以下代码和错误:

interface Movie {
id: number;
title: string;
createdAt?: Date;
...
}
...
const getCacheConn = async (): Promise<Collection<Document>> => {
const client = await MongoClient.connect(
`mongodb+srv://username:password@cluster.1234abcde.mongodb.net/${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>>可能是集合的错误类型吗?我四处搜索,但找不到有关此错误的信息。

试试这个:


interface Movie {
id: number;
title: string;
createdAt?: Date;
...
}
...
const connectDB = async () => {
const client = await MongoClient.connect(
`mongodb+srv://username:password@cluster.1234abcde.mongodb.net/${mydb}?retryWrites=true&w=majority`
);
return client.db()
};
const cacheMovies = async (movies: Movie[]) => {
...
const db = await connectDB;
db.collection(dbConn).insertMany(movies)
};

相关内容

最新更新