mongodb#MongoError TypeScript Examples
The following examples show how to use
mongodb#MongoError.
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: mongodb.ts From BotANF with GNU General Public License v3.0 | 6 votes |
export async function connect(_logger: any = logger) {
return new Promise((resolve, reject) => {
mongoClient?.connect((err: MongoError, client: MongoClient) => {
if (err) {
_logger.log(
`${err.name}${err.errmsg}`,
logLevel.warning,
"mongodb"
);
reject(err);
}
resolve(client);
});
});
}
Example #2
Source File: mongodb.ts From BotANF with GNU General Public License v3.0 | 6 votes |
export async function getSettings(_logger: any = logger) {
if (!mongoClient.isConnected()) await connect();
return new Promise((resolve, reject) => {
const collection = mongoClient
.db(databaseName, {
noListener: true,
returnNonCachedInstance: true,
})
.collection("Config");
collection.findOne(
{ name: "Config" },
(err: MongoError, result: any) => {
if (err) {
logger.log(
`Something went wrong while trying to get the configuration from the collection.\n${err.name}${err.errmsg}`,
logLevel.warning,
"mongodb"
);
reject(err);
}
resolve(result);
}
);
});
}
Example #3
Source File: mongodb.ts From BotANF with GNU General Public License v3.0 | 6 votes |
/**
* This is just for the test command and will be removed later.
*/
export async function getTextFromMongoDB(_logger: any = logger) {
if (!mongoClient.isConnected()) await connect();
return new Promise((resolve, reject) => {
const collection = mongoClient
.db(databaseName, { returnNonCachedInstance: false })
.collection("test");
collection.findOne(
{ name: "delivery" },
(err: MongoError, result: any) => {
if (err) {
logger.log(
`Something went wrong while trying to get the configuration from the collection.\n${err.name}${err.errmsg}`,
logLevel.warning,
"mongodb"
);
reject(err);
}
resolve(result);
}
);
});
}
Example #4
Source File: create-indexes-for-collection.ts From metroline with GNU General Public License v3.0 | 6 votes |
async function createIndexIfNotExists(spec: MongoIndexSpec, collection: Collection) {
const indexName = spec.options.name;
const indexNamespace = `${chalk.blue(collection.collectionName)}.${chalk.cyan(indexName)}`;
const createIndex = () => collection.createIndex(spec.fieldOrSpec, spec.options);
try {
await createIndex();
logger.debug(`Configured index ${indexNamespace}`);
} catch (e) {
if (
e instanceof MongoError
&& (
e.code === MongoErrorCode.INDEX_OPTIONS_CONFLICT
|| e.code === MongoErrorCode.INDEX_KEY_SPECS_CONFLICT
)
) {
logger.debug(`Updating index ${indexNamespace}`);
const existingIndexes: IndexSpecification[] = await collection.listIndexes().toArray();
const indexWithSameName = existingIndexes.find(value => value.name === spec.options.name);
if (indexWithSameName) {
await collection.dropIndex(indexName);
} else {
const indexWithSameKey = findIndexWithSameKey(existingIndexes, spec.fieldOrSpec);
await collection.dropIndex(indexWithSameKey.name);
}
logger.debug(`Updated index ${indexNamespace}`);
await createIndex();
} else {
throw e;
}
}
}
Example #5
Source File: base.service.ts From codeclannigeria-backend with MIT License | 5 votes |
protected static throwMongoError(err: MongoError): void {
console.error(err);
throw new InternalServerErrorException(err, err.errmsg);
}
Example #6
Source File: create-indexes-for-collection.spec.ts From metroline with GNU General Public License v3.0 | 4 votes |
describe('configureIndexesForCollection', () => {
let collection: Collection;
beforeEach(() => {
collection = {
dropIndex: jest.fn(),
createIndex: jest.fn(),
listIndexes: () => ({ toArray: () => Promise.resolve([]) }) as Partial<CommandCursor> as any,
} as Partial<Collection> as any;
});
afterEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
});
it('should compute index name when not defined', async () => {
await configureIndexesForCollection(collection, [
{ fieldOrSpec: 'field' },
]);
expect(collection.createIndex).toHaveBeenCalledWith('field', { name: 'field' });
});
it('should compute index name when not defined (multi key)', async () => {
await configureIndexesForCollection(collection, [
{
fieldOrSpec: {
field1: 1.0,
field2: 1.0,
},
},
]);
expect(collection.createIndex).toHaveBeenCalledWith({
field1: 1.0,
field2: 1.0,
}, { name: 'field1_field2' });
});
it('should use given index name', async () => {
await configureIndexesForCollection(collection, [
{ fieldOrSpec: 'field', options: { name: 'name' } },
]);
expect(collection.createIndex).toHaveBeenCalledWith('field', { name: 'name' });
});
it('should replace existing index with same name', async () => {
let callCount = 0;
jest.spyOn(collection, 'createIndex').mockImplementation(() => {
callCount++;
if (callCount === 1) {
throw new MongoError({ code: 85 });
}
});
jest.spyOn(collection, 'listIndexes').mockReturnValue({ toArray: () => Promise.resolve([{ name: 'field' }]) } as Partial<CommandCursor> as any);
await configureIndexesForCollection(collection, [
{ fieldOrSpec: 'field' },
]);
expect(collection.dropIndex).toHaveBeenCalledWith('field');
expect((collection.createIndex as any as SpyInstance).mock.calls).toEqual([
['field', { name: 'field' }],
['field', { name: 'field' }],
]);
});
it('should replace existing index with conflicting key specs', async () => {
let callCount = 0;
jest.spyOn(collection, 'createIndex').mockImplementation(() => {
callCount++;
if (callCount === 1) {
throw new MongoError({ code: 86 });
}
});
jest.spyOn(collection, 'listIndexes').mockReturnValue({ toArray: () => Promise.resolve([{ name: 'field' }]) } as Partial<CommandCursor> as any);
await configureIndexesForCollection(collection, [
{ fieldOrSpec: 'field' },
]);
expect(collection.dropIndex).toHaveBeenCalledWith('field');
expect((collection.createIndex as any as SpyInstance).mock.calls).toEqual([
['field', { name: 'field' }],
['field', { name: 'field' }],
]);
});
it('should replace existing index with different name but same keys', async () => {
let callCount = 0;
jest.spyOn(collection, 'createIndex').mockImplementation(() => {
callCount++;
if (callCount === 1) {
throw new MongoError({ code: 85 });
}
});
const indexList = [
[{
name: 'index1',
key: { field: 1.0 },
}],
[],
];
jest.spyOn(collection, 'listIndexes').mockReturnValue({ toArray: jest.fn().mockImplementation(() => indexList.reverse().pop()) } as Partial<CommandCursor> as any);
await configureIndexesForCollection(collection, [
{ fieldOrSpec: 'field' },
]);
expect(collection.dropIndex).toHaveBeenCalledWith('index1');
expect((collection.createIndex as any as SpyInstance).mock.calls).toEqual([
['field', { name: 'field' }],
['field', { name: 'field' }],
]);
});
it('should replace existing text index with different name but same keys', async () => {
let callCount = 0;
jest.spyOn(collection, 'createIndex').mockImplementation(() => {
callCount++;
if (callCount === 1) {
throw new MongoError({ code: 85 });
}
});
const indexList = [
[{
name: 'index1',
weights: { field: 1.0 },
}],
[],
];
jest.spyOn(collection, 'listIndexes').mockReturnValue({ toArray: jest.fn().mockImplementation(() => indexList.reverse().pop()) } as Partial<CommandCursor> as any);
await configureIndexesForCollection(collection, [
{ fieldOrSpec: 'field' },
]);
expect(collection.dropIndex).toHaveBeenCalledWith('index1');
expect((collection.createIndex as any as SpyInstance).mock.calls).toEqual([
['field', { name: 'field' }],
['field', { name: 'field' }],
]);
});
it('should rethrow error when cannot create index', async () => {
jest.spyOn(collection, 'createIndex').mockImplementation(() => {
throw new MongoError('');
});
let error: any;
try {
await configureIndexesForCollection(collection, [
{ fieldOrSpec: 'field' },
]);
} catch (e) {
error = e;
}
expect(error).toBeDefined();
});
it('should drop indexes that are not specified anymore', async () => {
jest.spyOn(collection, 'listIndexes').mockReturnValue({
toArray: () => Promise.resolve([
{ name: 'name' },
]),
} as Partial<CommandCursor> as any);
await configureIndexesForCollection(collection, []);
expect(collection.dropIndex).toHaveBeenCalledWith('name');
});
it('should not drop native id index', async () => {
jest.spyOn(collection, 'listIndexes').mockReturnValue({
toArray: () => Promise.resolve([
{ name: '_id_' },
]),
} as Partial<CommandCursor> as any);
await configureIndexesForCollection(collection, []);
expect(collection.dropIndex).not.toHaveBeenCalled();
});
});