I'm successfully connecting and writing to my MongoDB collection but there is a type error I can't figure out. Code and error below:
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.
};
The 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.
Am I missing something? Is Promise<Collection<Document>>
perhaps the wrong type for a collection? I searched around but couldn't find info on this error.
CodePudding user response:
try this:
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(dbConn).insertMany(movies)
};