When I query with projections then I expect the type to be different. For example, my collection has documents of type User.
interface User {
_id?: ObjectId
username: string
foo: number
}
And when I query it, then I expect the result to be of type UserView
interface UserView {
_id: ObjectId
username: string
}
My Repository looks something like this.
class UserRepository {
private collection: Collection<User>
constructor(db: Db) {
this.collection = db.collection<User>('User')
}
public async getUserById(id: ObjectId): Promise<UserView | null> {
// Result has type User
const result = await this.collection
.findOne({ _id: ${ eq: id } }, { projection: { _id: 1, username: 1 })
}
}
Current solutions I can think of is that I create a new collection with each type like this.
this.collection = db.collection<User>('User')
this.viewCollection = db.collection<UserView>('User')
or leave the typing out and return the function like this:
public async getUserById(id: ObjectId): Promise<UserView | null> {
// Result has type Document
const result = await this.collection
.findOne({ _id: ${ eq: id } }, { projection: { _id: 1, username: 1 })
if (result) return result as Userview
return null
}
What's the best approach to have proper typing in my MongoDB queries with projections?