Last active
February 27, 2022 23:04
-
-
Save almeidx/74ede05cdebc1ba4a6fdfb0c03814eb9 to your computer and use it in GitHub Desktop.
Mongoose projection example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Schema, model } from 'mongoose'; | |
interface IThing { | |
field1: string; | |
field2: string; | |
} | |
(async () => { | |
const thingSchema = new Schema<IThing>({ | |
field1: String, | |
field2: String, | |
}); | |
const things = model('things', thingSchema); | |
// The second parameter should be typed as ('field1' | 'field2')[] or similar, instead of `any` | |
const proj = await things.findOne({}, ['field1', 'abc']); | |
proj?.field1; // This is allowed correctly | |
proj?.field2; // This should not be allowed, as the key will not be present due to the projection used | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Document, ObjectId, Schema, model } from 'mongoose'; | |
export type Projection< | |
Schema extends {}, | |
Keys extends keyof Schema, | |
Id = ObjectId | |
> = Omit<Schema, Exclude<keyof Schema, Keys>> & Document<Id>; | |
(async () => { | |
interface IThing { | |
field1: string; | |
field2: string; | |
} | |
const thingSchema = new Schema<IThing>({ | |
field1: String, | |
field2: String, | |
}); | |
const things = model('things', thingSchema); | |
const projectionKeys: (keyof IThing)[] = ['field1']; | |
const proj = (await things.findOne({}, projectionKeys)) as Projection<IThing, 'field1'>; | |
proj?.field1; | |
// Doesn't allow proj.field2 | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment