mongoose#Document TypeScript Examples
The following examples show how to use
mongoose#Document.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: model-methods.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Delete Data from Database of the Particular Model after Verification
*
* @async
* @param {Model} model - Model in the Database
* @param {Object} data - Data to be Deleted to Database
* @param {IUserDoc} admin - Admin user Document from Database
* @param {Readonly<IPolicy>[]} policies - Array of Policies Applicable for the Function
* @returns {Promise<boolean>} - always resolves to true or throws error
*/
export async function deleteDatafromDatabase<
U extends Document,
V extends Model<U>,
>(
model: V,
data: U,
admin: IUserDoc,
policies: Readonly<IPolicy>[],
): Promise<boolean> {
await checkPolicy(policies, admin);
await model.deleteOne({ _id: data._id });
return true;
}
Example #2
Source File: map.schema.ts From pebula-node with MIT License | 6 votes |
cast(value: any, doc: Document, init: boolean) {
if (value instanceof GtMap) {
return value;
}
if (init) {
const map = new GtMap(this[SCHEMA_CONTAINER], {}, this.path, doc, this.$__schemaType);
if (value instanceof global.Map) {
for (const key of value.keys()) {
map.$init(key, map.$__schemaType.cast(value.get(key), doc, true));
}
} else {
for (const key of Object.keys(value)) {
map.$init(key, map.$__schemaType.cast(value[key], doc, true));
}
}
return map;
}
return new GtMap(this[SCHEMA_CONTAINER], value, this.path, doc, this.$__schemaType);
}
Example #3
Source File: document-array-path.ts From pebula-node with MIT License | 6 votes |
cast(value: any, doc: Document, init: boolean, prev?: any, options?: any): any {
const casted = super.cast([], doc, init, prev, options);
const arr = !value
? []
: !Array.isArray(value) ? [value] : value
;
const container = this[SCHEMA_CONTAINER];
for (let i = 0, len = arr.length; i < len; i++) {
const source = arr[i];
if (! (source instanceof this.casterConstructor) ) {
let ctor = this.casterConstructor;
if (container.localInfo.discriminator) {
const discriminatorKey = container.localInfo.container.getSchemaOptions('discriminatorKey');
ctor = this.casterConstructor.discriminators[source[discriminatorKey]];
}
casted[i] = new ctor(source, casted, false, null, i, true);
} else {
casted[i] = source;
}
}
return casted;
}
Example #4
Source File: mixin.ts From pebula-node with MIT License | 6 votes |
export function GtQuery<QMIXIN>(...mixins: Array<Ctor<QMIXIN>>): <T, C>(Cls: Ctor<Document & T> & Model & C) => Ctor<Document & T> & C & Model<QMIXIN> {
return <T, C>(Cls: Ctor<Document & T> & Model & C) => {
if (mixins.length > 0) {
class QueryHelper { }
mixObjects(QueryHelper.prototype, mixins.map(m => m.prototype));
mixObjects(QueryHelper, mixins);
gtSchemaStore.getCreate(Cls).defineQueryHelper(QueryHelper);
}
return Cls as any;
}
}
Example #5
Source File: auth.schema.ts From NextJS-NestJS-GraphQL-Starter with MIT License | 6 votes |
@ObjectType()
export class Session extends Document {
@Field(() => ID, { nullable: false })
readonly _id: string;
@Field()
readonly userAgent: string;
@Field({ nullable: false })
readonly token: string;
@Field({ nullable: false })
readonly user: string;
}
Example #6
Source File: dog.schema.ts From nestjs-tenancy with MIT License | 6 votes |
@Schema()
export class Dog extends Document {
@Prop()
name: string;
@Prop()
age: number;
@Prop()
breed: string;
}
Example #7
Source File: cat.schema.ts From nestjs-tenancy with MIT License | 6 votes |
@Schema()
export class Cat extends Document {
@Prop()
name: string;
@Prop()
age: number;
@Prop()
breed: string;
}
Example #8
Source File: user.schema.ts From NextJS-NestJS-GraphQL-Starter with MIT License | 6 votes |
@ObjectType()
export class User extends Document {
@Field(_type => ID, { nullable: false })
readonly _id: string;
@Field({ nullable: true })
readonly email: string;
@Field({ nullable: false })
readonly name: string;
@Field({ nullable: false })
readonly permalink: string;
@Field({ nullable: false })
readonly active: boolean;
@Field()
readonly githubId: string;
@Field()
readonly redditId: string;
@Field({ nullable: true })
readonly avatar?: string;
@Field({ nullable: true })
readonly bio?: string;
@Field(_type => Roles, { nullable: false })
readonly role: Roles;
}
Example #9
Source File: model-methods.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Add Data into Database of the Particular Model after Verification
*
* @async
* @param {Model} model - Model in the Database
* @param {Object} data - Data to be Added to Database
* @param {IUserDoc} admin - Admin user Document from Database
* @param {Readonly<IPolicy>[]} policies - Array of Policies Applicable for the Function
* @returns {Promise<Document>} - Saved Document
*/
export async function addDatatoDatabase<
T,
U extends Document,
V extends Model<U>,
>(
model: V,
data: T,
admin: IUserDoc,
policies: Readonly<IPolicy>[],
): Promise<U> {
await checkPolicy(policies, admin);
const newData = new model(data);
const savedData = await newData.save();
return savedData;
}
Example #10
Source File: model-methods.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Edit Data in Database of the Particular Model after Verification
*
* @param {Model} model - Model in the Database
* @param {Object} data - Data Document from the Database
* @param {Object} modifiedData - Modified Data
* @param {IUserDoc} admin - Admin user Document from Database
* @param {Readonly<IPolicy>[]} policies - Array of Policies Applicable for the Function
* @returns {Promise<boolean>} - always resolves to true or throws error
*/
export async function editDatainDatabase<
U extends Document,
V extends Model<U>,
>(
model: V,
data: U,
modifiedData: UpdateQuery<U>,
admin: IUserDoc,
policies: Readonly<IPolicy>[],
): Promise<boolean> {
await checkPolicy(policies, admin);
await model.updateOne({ _id: data._id }, modifiedData);
return true;
}
Example #11
Source File: ClientTaskManager.ts From Asena with MIT License | 6 votes |
private async executeTask<D extends Document>(task: keyof ClientTask, items: D[]): Promise<void>{
let executable: StructureTask
switch(task){
case 'Raffle':
executable = this.raffleTask
break
case 'Survey':
executable = this.surveyTask
break
}
executable.onExecute(items).then(void 0)
}
Example #12
Source File: Mongo.ts From ModMail with MIT License | 6 votes |
async getLog(id: string, type: 'ID' | 'USER' | 'CHANNEL' = 'CHANNEL', open = true): Promise<LogDocument | null> {
const filter: _FilterQuery<_AllowStringsForIds<Pick<Pick<Document<unknown>, '_id'>, '_id'>>> = {};
if (type === 'ID')
filter._id = id;
else if (type === 'USER')
filter['recipient.id'] = id;
else
filter.channelID = id;
filter.open = open;
filter.botID = this.caller.bot.user.id;
return await Log.findOne(filter)
.then((data: LogDocument) => data as LogDocument)
.catch(() => null);
}
Example #13
Source File: edit-history.ts From tams-club-cal with MIT License | 6 votes |
/**
* Creates a history object given the data of the newly created resource.
* If it's a new history entry (default), it will simply convert the fields of the data
* passed in to a key/value pair, or else it will run the diff between the
* previous and new data (in req.body).
*
* @param req Express request object
* @param data Resource data (either new data or previous data depending on "isNew")
* @param resource Resource name
* @param id UUIDv4 for the resource
* @param historyId UUIDv4 for the history object
* @param isNew True if a new resource (default: true)
* @param club Will use club object instead of req.body to get diff if defined
*/
export async function createHistory(
req: Request,
data: object,
resource: string,
id: string,
historyId: string,
isNew: boolean = true,
club?: ClubObject
): Promise<Document> {
return new History({
id: historyId,
resource,
editId: id,
time: new Date().valueOf(),
editor: await getEditor(req),
fields: isNew ? objectToHistoryObject(data) : getDiff(data, club || req.body),
});
}
Example #14
Source File: fields-picker.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Parse SchemType Objects to handle Custom Schema Options
*
* @param {Schema} schema - Mongoose Object Schema
* @param {string} criteria - Custom Option in the Schema to Check
* @returns {string[]} - Array of path names passing the criteria
*/
export default function <T, U extends Document, V extends Model<U>>(
schema: Schema<U, V, T>,
criteria: string,
): string[] {
const pickedFields: string[] = [];
schema.eachPath((path: string, schemaType: SchemaType) => {
const keys = Object.keys(schemaType);
const props = Object.create(schemaType);
if (keys && props) {
const options = props['options'];
if (dotProp.has(options, criteria)) {
pickedFields.push(path);
}
}
});
return pickedFields;
}
Example #15
Source File: index.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Creates a Base64 Encoder Plugin which will add option to Encode Fields in a Schema
*
* @returns {Function} Base64 Plugin
*/
export default function <T, U extends Document, V extends Model<U>>(): (
schema: Schema<U, V, T>,
) => void {
const plugin = (schema: Schema<U, V, T>): void => {
const toEncodeFields: string[] = fieldsPicker<T, U, V>(
schema,
'base64encode',
);
schema.pre('validate', function (this: U, next: HookNextFunction) {
const encodedDoc = encodeFields<U>(this, toEncodeFields);
this.set(encodedDoc);
next();
});
schema.post('init', function (this: U) {
const decodedDoc = decodeFields<U>(this, toEncodeFields);
return decodedDoc;
});
};
return plugin;
}
Example #16
Source File: index.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Creates a Crypto Plugin which will add option to encrypt Fields in a Schema
*
* @returns {Function} Crypto Plugin
*/
export default function <T, U extends Document, V extends Model<U>>(): (
schema: Schema<U, V, T>,
) => void {
const plugin = (schema: Schema<U, V, T>): void => {
const encryptedFields: string[] = fieldsPicker<T, U, V>(schema, 'encrypt');
schema.pre('validate', function (this: U, next: HookNextFunction) {
const encryptedDoc = encryptFields(this, encryptedFields);
this.set(encryptedDoc);
next();
});
schema.post('init', function (this: U) {
const decryptedDoc = decryptFields<U>(this, encryptedFields);
return decryptedDoc;
});
};
return plugin;
}
Example #17
Source File: index.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* Creates a Hash Plugin which will add option to hash Fields using Bcrypt in a Schema
*
* @returns {Function} Hash Plugin
*/
export default function <T, U extends Document, V extends Model<U>>(): (
schema: Schema<U, V, T>,
) => void {
const plugin = (schema: Schema<U, V, T>): void => {
const toHashFields: string[] = fieldsPicker<T, U, V>(schema, 'hash');
schema.pre('validate', function (this: U, next: HookNextFunction) {
hashString<U>(this, toHashFields)
.then((hashedDoc) => {
this.set(hashedDoc);
next();
})
.catch((err) => {
console.log(err);
next(new Error('Password Hashing Failed'));
});
});
};
return plugin;
}
Example #18
Source File: clear-collection.ts From server with GNU General Public License v3.0 | 6 votes |
/**
* General Function to Clear a Collection by Deleting all the Records
*
* @param {Model} model - Mongoose Model
* @returns {Promise<IInlineResponse<string>>} - Response whether cleared or not
*/
export default async function <U extends Document, V extends Model<U>>(
model: V,
): Promise<IInlineResponse<string>> {
await model.deleteMany({});
return {
success: true,
data: 'Successfully Cleared the Collection',
error: null,
};
}
Example #19
Source File: tidbit.model.ts From frontend.ro with MIT License | 6 votes |
function sanitizeTidbit(tidbit: Document<TidbitI> & TidbitI): TidbitI {
const tidbitCopy = tidbit.toObject();
delete tidbitCopy._id;
tidbitCopy.items.forEach((item) => {
delete item._id;
});
delete tidbitCopy.views;
return tidbitCopy;
}
Example #20
Source File: certification.model.ts From frontend.ro with MIT License | 6 votes |
function sanitizeCertification(certification: Document<any, any, WIPPopulatedCertificationI> & WIPPopulatedCertificationI) {
// https://github.com/Automattic/mongoose/issues/2790
const sanitizedCertfication: WIPPopulatedCertificationI = JSON.parse(JSON.stringify(certification.toObject()));
sanitizedCertfication.user = SharedUserModel.sanitize(sanitizedCertfication.user);
sanitizedCertfication.lesson_exercises = sanitizedCertfication.lesson_exercises.map(lessonExercise => {
return SharedExerciseModel.sanitize(lessonExercise)
});
return sanitizedCertfication;
}
Example #21
Source File: certification.model.ts From frontend.ro with MIT License | 5 votes |
/**
* Store a certification into the Database and trigger a Lambda Function
* to generate it's corresponding assets: PDF and JPEG.
* > NOTE: this function is somewhat idempotent - in the sense that
* > multiple calls to this function don't create multiple Certifications,
* > instead they update the same one.
* @param userId string
* @param tutorial_id ObjectId
* @param dryRun boolean - whether to actually perform the tasks, or simply to log the result, without any side effects
* @returns
*/
async function createCertification(
userId: string,
tutorial_id: ObjectId,
dryRun = false
): Promise<mongoose.Document<any, any, CertificationI> & CertificationI> {
const SPAN = `[createCertification, userId=${userId}, tutorial_id=${tutorial_id}, dryRun=${dryRun}]`;
const tutorial = await Tutorial
.findById(tutorial_id)
.populate<{ lessons: LessonI[] }>("lessons");
if (tutorial === null) {
console.error(`${SPAN} couldn't find tutorial. Exiting.`);
return;
}
let certification: mongoose.Document<any, any, CertificationI> & CertificationI;
// Step 1: store certification into the DB
try {
certification = await storeCertificationData(tutorial, userId, dryRun);
} catch (err) {
console.error(`${SPAN} Certification couldn't be saved in DB`, err);
return;
}
try {
certification = await refreshCertificationAssets(certification, dryRun);
} catch (err) {
console.error(`${SPAN} Certification assets couldn't be generated.`, err);
return;
}
console.info(`${SPAN} successfully created certification`);
return certification;
}
Example #22
Source File: setup.ts From server with GNU General Public License v3.0 | 5 votes |
/**
* coool
*
* @param {IBaseModel<Document>} model - coool
*/
constructor(model: IBaseModel<T>) {
(this.router = express.Router()), (this.model = model);
}
Example #23
Source File: map.schema.ts From pebula-node with MIT License | 5 votes |
discriminator<U extends Document>(name: string, schema: Schema, value?: string): Model<U> {
const created = this.$__schemaType.discriminator(name, schema, value);
return created as any;
}
Example #24
Source File: document-array-path.ts From pebula-node with MIT License | 5 votes |
discriminator<U extends Document>(name: string, schema: Schema, value?: string): Model<U> {
const created = extendEmbeddedDocument(super.discriminator(name, schema, value));
this.casterConstructor.discriminators[name] = created;
return created as any;
}
Example #25
Source File: schema.ts From pebula-node with MIT License | 5 votes |
export function GtDocument(metadata?: GtDocumentMetadataArgs): ClassDecoratorOf<Document, Model> {
return (target: Function) => {
gtSchemaStore.getCreate(target).setMetadata(GtDocumentMetadata, metadata || {}, { target });
};
}
Example #26
Source File: carsController.ts From node-fastify-mongo-api with MIT License | 5 votes |
getCars = async (req: FastifyRequest, reply: FastifyReply<ServerResponse>): Promise<Document[]> => {
try {
const cars = await Car.find();
return cars;
} catch (err) {
throw boom.boomify(err);
}
}
Example #27
Source File: user.schema.ts From nestjs-seeder with MIT License | 5 votes |
@Schema()
export class User extends Document {
// @Factory will automatically inject faker to the function that you pass.
@Factory(faker => faker.random.arrayElement(['male', 'female']))
@Prop({ required: true })
gender: string;
// You could get the previously generated value using the passed context.
@Factory((faker, ctx) => ({
first: faker.name.firstName(ctx.gender === 'male' ? 0 : 1),
last: faker.name.lastName(ctx.gender === 'male' ? 0 : 1),
}))
@Prop(
raw({
first: { type: String, required: true },
last: { type: String, required: true },
}),
)
name: Record<string, string>;
// You could also use custom function without faker.
@Factory(() => {
const minAge = 18;
const maxAge = 30;
return Math.round(Math.random() * (maxAge - minAge) + minAge);
})
@Prop({ required: true })
age: number;
// You could also use static value.
@Factory('admin')
@Prop({ required: true })
role: string;
// If you pass predefined values to the `generate` function, you will be
// able to access it in the context.
@Factory((faker, ctx) => `${faker.address.streetAddress()} ${ctx.zipCode}`)
@Prop({ required: true })
address: string;
}
Example #28
Source File: typegoose-middleware.ts From convoychat with GNU General Public License v3.0 | 5 votes |
function convertDocument(doc: Document) {
const convertedDocument = doc.toObject();
const DocumentClass = getClassForDocument(doc)!;
Object.setPrototypeOf(convertedDocument, DocumentClass.prototype);
return convertedDocument;
}
Example #29
Source File: hooks.ts From davinci with MIT License | 5 votes |
createRegisterHooks = (hooksList, stage: Stage) => <T>(mongooseSchema: T, handler): void => {
const isReadHook = hooksList === READ_HOOKS;
const isWriteHook = hooksList === WRITE_HOOKS;
const isDeleteHook = hooksList === DELETE_HOOKS;
const hasContextInOptions = (hook: Hook): boolean =>
isReadHook || isDeleteHook || ['findOneAndUpdate', 'update', 'updateMany', 'updateOne'].includes(hook);
const hasContextInSaveOptions = (hook: Hook): boolean =>
isWriteHook && !['findOneAndUpdate', 'update', 'updateMany', 'updateOne'].includes(hook);
hooksList.forEach(hook =>
mongooseSchema[stage](hook, async function hookHandlerWrapper(result, ...rest) {
let context;
if (hasContextInOptions(hook)) {
context = this.options?.context;
if (this.options?.skipHooks) {
return;
}
}
if (hasContextInSaveOptions(hook)) {
// eslint-disable-next-line no-underscore-dangle
context = this.$__.saveOptions?.context;
// eslint-disable-next-line no-underscore-dangle
if (this.$__.saveOptions?.skipHooks) {
return;
}
}
const args = createHandlerArgs<T, T & Document>(stage, hook, {
isReadHook,
isWriteHook,
isDeleteHook,
thisObj: this,
result,
context,
rest
});
if (args) {
await handler(args);
}
})
);
}