Skip to content

Instantly share code, notes, and snippets.

@almeidx
Last active February 27, 2022 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save almeidx/74ede05cdebc1ba4a6fdfb0c03814eb9 to your computer and use it in GitHub Desktop.
Save almeidx/74ede05cdebc1ba4a6fdfb0c03814eb9 to your computer and use it in GitHub Desktop.
Mongoose projection example
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
})();
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