Browse Source

Error: $or must be an array (#778)

pull/1/head
Alexandr Velikiy 5 years ago committed by rozetko
parent
commit
5ea0a058fc
  1. 3
      server/src/services/data_layer/basedb.ts
  2. 30
      server/src/services/data_layer/mongodb.ts

3
server/src/services/data_layer/basedb.ts

@ -13,3 +13,6 @@ export interface DbQueryWrapper {
dbRemoveOne(collection: dbCollection, query: string | object): Promise<boolean>;
dbRemoveMany(collection: dbCollection, query: string[] | object): Promise<number>;
}
export class QueryExecutionError extends Error {
}

30
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);
try {
const docs = await collection.find(query).sort(sortQuery).toArray();
// TODO: move to utils
docs.forEach(doc => {
if(doc !== null) {
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<string | object>): Promise<boolean> {
@ -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;
}

Loading…
Cancel
Save