diff --git a/server/src/services/data_layer/basedb.ts b/server/src/services/data_layer/basedb.ts index bfac949..4d74b22 100644 --- a/server/src/services/data_layer/basedb.ts +++ b/server/src/services/data_layer/basedb.ts @@ -13,3 +13,6 @@ export interface DbQueryWrapper { dbRemoveOne(collection: dbCollection, query: string | object): Promise; dbRemoveMany(collection: dbCollection, query: string[] | object): Promise; } + +export class QueryExecutionError extends Error { +} diff --git a/server/src/services/data_layer/mongodb.ts b/server/src/services/data_layer/mongodb.ts index 223aec6..141afbb 100644 --- a/server/src/services/data_layer/mongodb.ts +++ b/server/src/services/data_layer/mongodb.ts @@ -1,4 +1,4 @@ -import { DbQueryWrapper } from './basedb'; +import { DbQueryWrapper, QueryExecutionError } from './basedb'; import { Collection, FilterQuery, ObjectID } from 'mongodb'; import { wrapIdToMongoDbQuery, wrapIdsToMongoDbQuery, isEmptyArray } from './utils'; @@ -84,15 +84,20 @@ export class MongoDbQueryWrapper implements DbQueryWrapper { if(isEmptyArray(query)) { return []; } + query = convertQueryToMongoFormat(query); query = wrapIdsToMongoDbQuery(query); - const docs = await collection.find(query).sort(sortQuery).toArray(); - // TODO: move to utils - docs.forEach(doc => { - if(doc !== null) { - doc._id = doc._id.toString(); - } - }); - return docs; + try { + const docs = await collection.find(query).sort(sortQuery).toArray(); + docs.forEach(doc => { + if (doc !== null) { + doc._id = doc._id.toString(); + } + }); + return docs; + } catch(error) { + console.error(`Can't get query result for query ${JSON.stringify(query)} in collection: ${collection.namespace}`); + throw new QueryExecutionError(`MongoDB query error: ${error.message}`); + } } async dbRemoveOne(collection: Collection, query: FilterQuery): Promise { @@ -115,3 +120,22 @@ export class MongoDbQueryWrapper implements DbQueryWrapper { return deleted.deletedCount; } } + +function convertQueryToMongoFormat(query: any): object { + if(query.$or !== undefined) { + query.$or = convertQueryFieldToMongoFormat(query.$or); + } + if(query.$and !== undefined) { + query.$and = convertQueryFieldToMongoFormat(query.$and); + } + return query; +} + +function convertQueryFieldToMongoFormat(query: object): object[] { + let mongoQuery = []; + for(const key in query) { + const newObject = _.pick(query, key); + mongoQuery.push(newObject); + } + return mongoQuery; +}