mongoose#Query TypeScript Examples
The following examples show how to use
mongoose#Query.
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: MongoPaginator.ts From node-experience with MIT License | 6 votes |
constructor(documentQuery: Query<any[], any>, criteria: ICriteria, config: IPaginatorConfig = { metadata: {}, helper: null })
{
this.documentQuery = documentQuery;
this.filter = criteria.getFilter();
this.sort = criteria.getSort();
this.pagination = criteria.getPagination();
this.offset = this.pagination.getOffset();
this.limit = this.pagination.getLimit();
this.metadata = config?.metadata ?? {};
this.helper = config?.helper ?? null;
}
Example #2
Source File: FileMongoRepository.ts From node-experience with MIT License | 6 votes |
async list(criteria: ICriteria): Promise<IPaginator>
{
const queryBuilder: Query<IFile[], IFile> = this.repository.find();
const filter = criteria.getFilter();
if (filter.has(FileFilter.NAME))
{
const name: string = filter.get(FileFilter.NAME);
const rsearch = new RegExp(name, 'g');
void queryBuilder.where(FileFilter.NAME).regex(rsearch);
}
return new MongoPaginator(queryBuilder, criteria);
}
Example #3
Source File: ItemMongoRepository.ts From node-experience with MIT License | 6 votes |
async list(criteria: ICriteria): Promise<IPaginator>
{
const queryBuilder: Query<IItem[], IItem> = this.repository.find();
const filter = criteria.getFilter();
if (filter.has(ItemFilter.TYPE))
{
const type = filter.get(ItemFilter.TYPE);
void queryBuilder.where(ItemFilter.TYPE).equals(type);
}
if (filter.has(ItemFilter.NAME))
{
const name: string = filter.get(ItemFilter.NAME);
const rSearch = new RegExp(name, 'g');
void queryBuilder.where(ItemFilter.NAME).regex(rSearch);
}
void queryBuilder.populate(this.populate);
return new MongoPaginator(queryBuilder, criteria);
}
Example #4
Source File: NotificationMongoRepository.ts From node-experience with MIT License | 6 votes |
async list(criteria: ICriteria): Promise<IPaginator>
{
const queryBuilder: Query<INotification[], INotification> = this.repository.find();
const filter = criteria.getFilter();
if (filter.has(NotificationFilter.KIND))
{
const type = filter.get(NotificationFilter.KIND);
void queryBuilder.where(NotificationFilter.KIND).equals(type);
}
if (filter.has(NotificationFilter.NAME))
{
const name: string = filter.get(NotificationFilter.NAME);
const rsearch = new RegExp(name, 'g');
void queryBuilder.where(NotificationFilter.NAME).regex(rsearch);
}
return new MongoPaginator(queryBuilder, criteria);
}
Example #5
Source File: RoleMongoRepository.ts From node-experience with MIT License | 6 votes |
async list(criteria: ICriteria): Promise<IPaginator>
{
const queryBuilder: Query<IRole[], IRole> = this.repository.find();
const filter = criteria.getFilter();
if (filter.has(RoleFilter.ENABLE))
{
const _enable = filter.get(RoleFilter.ENABLE);
const enable: boolean = _enable !== 'false';
void queryBuilder.where(RoleFilter.ENABLE).equals(enable);
}
if (filter.has(RoleFilter.NAME))
{
const name = filter.get(RoleFilter.NAME);
const rSearch = new RegExp(name, 'g');
void queryBuilder.where(RoleFilter.NAME).regex(rSearch);
}
if (filter.has(RoleFilter.SLUG))
{
const slug = filter.get(RoleFilter.SLUG);
const rSearch = new RegExp(slug, 'g');
void queryBuilder.where(RoleFilter.SLUG).regex(rSearch);
}
void queryBuilder.where(RoleFilter.SLUG).ne(Roles.SUPER_ADMIN.toLowerCase());
return new MongoPaginator(queryBuilder, criteria);
}
Example #6
Source File: UserMongoRepository.ts From node-experience with MIT License | 6 votes |
async list(criteria: ICriteria): Promise<IPaginator>
{
const queryBuilder: Query<IUser[], IUser> = this.repository.find({});
const filter = criteria.getFilter();
if (filter.has(UserFilter.ENABLE))
{
const _enable = filter.get(UserFilter.ENABLE);
const enable: boolean = _enable !== 'false';
void queryBuilder.where(UserFilter.ENABLE).equals(enable);
}
if (filter.has(UserFilter.EMAIL))
{
const email = filter.get(UserFilter.EMAIL);
const rsearch = new RegExp(email, 'g');
void queryBuilder.where(UserFilter.EMAIL).regex(rsearch);
}
if (filter.has(UserFilter.IS_SUPER_ADMIN))
{
const isSuperAdmin: boolean = filter.get(UserFilter.IS_SUPER_ADMIN);
void queryBuilder.where(UserFilter.IS_SUPER_ADMIN).equals(isSuperAdmin);
}
void queryBuilder.populate('roles');
return new MongoPaginator(queryBuilder, criteria);
}
Example #7
Source File: MongoPaginator.ts From node-experience with MIT License | 5 votes |
private documentQuery: Query<any[], any>;
Example #8
Source File: TokenMongoRepository.ts From node-experience with MIT License | 5 votes |
async list(criteria: ICriteria): Promise<IPaginator>
{
const queryBuilder: Query<ITokenDocument[], ITokenDocument> = this.repository.find();
return new MongoPaginator(queryBuilder, criteria);
}
Example #9
Source File: users.repository.ts From nest-js-boilerplate with MIT License | 5 votes |
public getAll(): Query<UserDocument[], UserDocument> {
return this.usersModel.find().lean();
}
Example #10
Source File: users.repository.ts From nest-js-boilerplate with MIT License | 5 votes |
public getVerifiedUsers(): Query<UserDocument[], UserDocument> {
return this.usersModel.find({ verified: true }).lean();
}
Example #11
Source File: users.service.ts From nest-js-boilerplate with MIT License | 5 votes |
getAllVerified(): Query<UserDocument[], UserDocument> {
return this.usersRepository.getVerifiedUsers();
}
Example #12
Source File: base.service.ts From codeclannigeria-backend with MIT License | 5 votes |
count(filter = {}): Query<number> {
filter = { ...filter, isDeleted: { $ne: true } };
return this.EntityModel.countDocuments(filter);
}
Example #13
Source File: hooks.ts From davinci with MIT License | 4 votes |
createHandlerArgs = <Context = unknown, ResultType = unknown>(
stage: Stage,
hookName: Hook,
{
isReadHook,
isWriteHook,
isDeleteHook,
thisObj,
result,
rest,
context
}: {
isReadHook: boolean;
isWriteHook: boolean;
isDeleteHook: boolean;
thisObj: Document | Query<ResultType, ResultType & Document>;
result?: any;
rest?: unknown[];
context?: Context;
}
):
| PreArgs<ResultType>
| AfterArgs<ResultType>
| AfterRawResultArgs<ResultType>
| DocumentPreArgs
| DocumentPostArgs
| undefined => {
const operation = (isReadHook && 'read') || (isWriteHook && 'write') || (isDeleteHook && 'delete');
// createPreArgs creates the arguments for `before(Read|Write|Delete)` hooks
const createPreArgs = (): PreArgs<Context, ResultType> => ({
query: thisObj as Query<ResultType, ResultType & Document>,
hookName,
context
});
// createAfterArgs creates the arguments for `after(Read|Write|Delete)` hooks
const createAfterArgs = (): AfterArgs<Context, ResultType> => ({
query: thisObj as Query<ResultType, ResultType & Document>,
hookName,
context,
result
});
// createAfterRawResultArgs creates the arguments for `after(Read|Write|Delete)` hooks triggered by atomic operations
const createAfterRawResultArgs = (): AfterRawResultArgs<Context, ResultType> => ({
query: thisObj as Query<ResultType, ResultType & Document>,
hookName,
context,
rawResult: result
});
// createDocumentPreArgs creates the arguments for `before(Read|Write|Delete)` hooks triggered by
// document middlewares: https://mongoosejs.com/docs/middleware.html
const createDocumentPreArgs = (): DocumentPreArgs => ({ hookName, context, doc: thisObj as Document });
// createDocumentPostArgs creates the arguments for `after(Read|Write|Delete)` hooks triggered by
// document middlewares: https://mongoosejs.com/docs/middleware.html
const createDocumentPostArgs = (): DocumentPostArgs => ({
result: thisObj as Document,
hookName,
context,
doc: rest[1] as Document
});
const argsSwitch = {
countDocuments: {
pre: {
read: createPreArgs
},
post: {
read: () => ({ query: thisObj, hookName, context, count: result })
}
},
find: {
pre: {
read: createPreArgs
},
post: {
read: createAfterArgs
}
},
findOne: {
pre: {
read: createPreArgs
},
post: {
read: createAfterArgs
}
},
findOneAndUpdate: {
pre: {
read: createPreArgs,
write: createPreArgs
},
post: {
read: createAfterArgs,
write: createAfterArgs
}
},
update: {
pre: {
read: createPreArgs,
write: createPreArgs
},
post: {
write: createAfterRawResultArgs
}
},
updateMany: {
pre: {
read: createPreArgs,
write: createPreArgs
},
post: {
write: createAfterRawResultArgs
}
},
updateOne: {
pre: {
read: createPreArgs,
write: createPreArgs
},
post: {
write: createAfterRawResultArgs
}
},
findOneAndDelete: {
pre: {
delete: createPreArgs
},
post: {
delete: createAfterArgs
}
},
findOneAndRemove: {
pre: {
delete: createPreArgs
},
post: {
delete: createAfterArgs
}
},
deleteOne: {
pre: {
delete: createPreArgs
},
post: {
delete: createAfterRawResultArgs
}
},
deleteMany: {
pre: {
delete: createPreArgs
},
post: {
delete: createAfterRawResultArgs
}
},
remove: {
pre: {
delete: createDocumentPreArgs
},
post: {
delete: createDocumentPostArgs
}
},
save: {
pre: {
write: createDocumentPreArgs
},
post: {
write: createDocumentPostArgs
}
}
};
return argsSwitch?.[hookName]?.[stage]?.[operation]?.();
}
Example #14
Source File: course.service.spec.ts From edu-server with MIT License | 4 votes |
describe('CourseService', () => {
let service: CourseService;
let model: Model<CourseDoc>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CourseService,
{
provide: getModelToken('Course'),
useValue: {
new: jest.fn().mockResolvedValue(mockCourse),
constructor: jest.fn().mockResolvedValue(mockCourse),
find: jest.fn(),
populate: jest.fn(),
findOne: jest.fn(),
findById: jest.fn(),
update: jest.fn(),
create: jest.fn(),
remove: jest.fn(),
exec: jest.fn(),
findByIdAndUpdate: jest.fn(),
},
},
{
provide: getModelToken('Schedule'),
useValue: {},
},
{
provide: getModelToken('Review'),
useValue: {},
},
{
provide: getModelToken('Doubt'),
useValue: {},
},
{
provide: getModelToken('DoubtAnswer'),
useValue: {},
},
{
provide: getModelToken('Assignment'),
useValue: {},
},
{
provide: getModelToken('Lecture'),
useValue: {},
},
{
provide: getModelToken('Mentor'),
useValue: {},
},
],
}).compile();
service = module.get<CourseService>(CourseService);
model = module.get<Model<CourseDoc>>(getModelToken('Course'));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
beforeEach(() => {
jest.setTimeout(25000);
});
afterEach(() => {
jest.setTimeout(5000);
jest.clearAllMocks();
});
describe('Testing courseservice after mock', () => {
const _id = '60bca010d17d463dd09baf9b';
const courseDocArray = [mockCourseDoc({}, _id)];
// Test for testing the service for returning all courses
it('should return all courses', async () => {
jest.spyOn(model, 'find').mockReturnValue({
exec: jest.fn().mockResolvedValueOnce(courseDocArray),
} as any);
const courses = await service.findAllCourses();
const courseArray = [{ ...mockCourse(), _id }];
expect(courses).toEqual(courseArray);
});
// Test for testing the service for finding a Course by id
it('should getOne Course by id', async () => {
jest.spyOn(model, 'findById').mockReturnValueOnce(
createMock<Query<CourseDoc, CourseDoc>>({
exec: jest.fn().mockResolvedValueOnce(mockCourseDoc()),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const findMockCourse = {
...mockCourse(),
_id: '6079f573062890a5e2cad207',
};
const foundCourse = await service.findCourseDummy(id);
expect(foundCourse).toEqual(findMockCourse);
});
// Test for testing the service for updating a Course
it('should update a Course successfully', async () => {
jest.spyOn(model, 'findByIdAndUpdate').mockReturnValueOnce(
createMock<Query<CourseDoc, CourseDoc>>({
exec: jest.fn().mockResolvedValueOnce({
name: 'DSA with JAVA',
originalPrice: 100,
active: false,
couponCode: 'CFC424',
video_num: 0,
duration: '11.5 hours',
assignments: [],
start_date: '2020-02-05T06:35:22.000Z',
end_date: '2020-02-05T06:35:22.000Z',
sharable_link: 'https://java.com',
mentor: [],
tags: [TagType.WEB_DEV],
courseDetails:
'The course gives a hands on learning experience on Rest APIs and Javascript',
courseLevel: courseLevelType.BEGINNER,
courseThumbnail: 'https://codeforcause.org/courses',
courseTrailerUrl: 'https://codeforcause.org/courseTrailer',
no_of_enrollments: 1000,
student_num: 2,
schedule: [],
reviews: [],
doubts: [],
_id: '6079f573062890a5e2cad207',
crossPrice: 120,
courseShortDescription: 'Short description--',
courseLongDescription: 'Long description--',
rating: 5,
prerequisites: [],
skills: [],
whatYouWillLearn: [],
certificateUrl: 'https://codeforcause.org/certificate',
isUpcoming: false,
}),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const updateCoursedto: UpdateCourseDTO = {
name: 'DSA with JAVA',
originalPrice: 100,
active: false,
couponCode: 'CFC424',
video_num: 0,
duration: '11.5 hours',
start_date: new Date('2020-02-05T06:35:22.000Z'),
end_date: new Date('2020-02-05T06:35:22.000Z'),
sharable_link: 'https://java.com',
tags: [TagType.WEB_DEV],
courseDetails:
'The course gives a hands on learning experience on Rest APIs and Javascript',
courseLevel: courseLevelType.BEGINNER,
courseThumbnail: 'https://codeforcause.org/courses',
courseTrailerUrl: 'https://codeforcause.org/courseTrailer',
no_of_enrollments: 1000,
crossPrice: 120,
courseShortDescription: 'Short description--',
courseLongDescription: 'Long description--',
rating: 5,
prerequisites: [],
skills: [],
whatYouWillLearn: [],
certificateUrl: 'https://codeforcause.org/certificate',
isUpcoming: false,
};
const updatedCourse = await service.editCourse(id, updateCoursedto);
const _id = '6079f573062890a5e2cad207';
const updatedCourseFinal = { ...mockCourse(), ...updatedCourse, _id };
expect(updatedCourse).toEqual(updatedCourseFinal);
});
});
});
Example #15
Source File: mentor.service.spec.ts From edu-server with MIT License | 4 votes |
describe('MentorService', () => {
let service: MentorService;
let model: Model<MentorDoc>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
MentorService,
{
provide: getModelToken('Mentor'),
useValue: {
new: jest.fn().mockResolvedValue(mockMentor),
constructor: jest.fn().mockResolvedValue(mockMentor),
find: jest.fn(),
populate: jest.fn(),
findOne: jest.fn(),
findById: jest.fn(),
update: jest.fn(),
create: jest.fn(),
remove: jest.fn(),
exec: jest.fn(),
findByIdAndUpdate: jest.fn(),
},
},
{
provide: getModelToken('Course'),
useValue: {},
},
],
}).compile();
service = module.get<MentorService>(MentorService);
model = module.get<Model<MentorDoc>>(getModelToken('Mentor'));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
beforeEach(() => {
jest.setTimeout(10000);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('Testing MentorService after mock', () => {
const _id = '60bca010d17d463dd09baf9b';
const mentorDocArray = [mockMentorDoc({}, _id)];
// Test for testing the service for returning all mentors
it('should return all mentors', async () => {
jest.spyOn(model, 'find').mockReturnValue({
exec: jest.fn().mockResolvedValueOnce(mentorDocArray),
} as any);
// console.log(mentorDocArray);
const mentors = await service.getAllMentor();
// console.log(mentors);
const mentorArray = [{ ...mockMentor(), _id }];
expect(mentors).toEqual(mentorArray);
});
// Test for testing the service for finding a Mentor by id
it('should getOne Mentor by id', async () => {
jest.spyOn(model, 'findById').mockReturnValueOnce(
createMock<Query<MentorDoc, MentorDoc>>({
exec: jest.fn().mockResolvedValueOnce(mockMentorDoc()),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const findMockMentor = {
...mockMentor(),
_id: '6079f573062890a5e2cad207',
};
const foundMentor = await service.findMentorById(id);
expect(foundMentor).toEqual(findMockMentor);
});
// Test for testing the service for updating a Mentor
it('should update a Mentor successfully', async () => {
jest.spyOn(model, 'findByIdAndUpdate').mockReturnValueOnce(
createMock<Query<MentorDoc, MentorDoc>>({
exec: jest.fn().mockResolvedValueOnce({
_id: '6079f573062890a5e2cad207',
name: 'Abhishek Kumar',
email: '[email protected]',
courses: [],
number_of_students: 100000,
mentorPhoto: 'https://codeforcause.org/static/images',
aboutMe: 'I am a full stack developer',
techStack: ['MERN', 'Java', 'Python'],
}),
}),
);
const id = new mongoose.Schema.Types.ObjectId('22', 0, 'rtex');
const updatedMentordto: UpdateMentorDTO = {
name: 'Abhishek Kumar',
email: '[email protected]',
number_of_students: 100000,
mentorPhoto: 'https://codeforcause.org/static/images',
aboutMe: 'I am a full stack developer',
techStack: ['MERN', 'Java', 'Python'],
};
const updatedMentor = await service.updateMentor(id, updatedMentordto);
const _id = '6079f573062890a5e2cad207';
const updatedMentorFinal = { ...mockMentor(), ...updatedMentor, _id };
expect(updatedMentor).toEqual(updatedMentorFinal);
});
});
});