Skip to content

Commit

Permalink
feature: adds export for UpdateCommand to allow custom queries with M…
Browse files Browse the repository at this point in the history
…ongoDB (#411)

Signed-off-by: Marc J. Schmidt <marc@marcjschmidt.de>
Co-authored-by: Marc J. Schmidt <marc@marcjschmidt.de>

There are a lot more commands for mongo's client, but we start exporting them one by one as we see use-cases coming in.
  • Loading branch information
colorcube committed Apr 12, 2023
1 parent 058f090 commit 4d627d2
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/mongo/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
*
* You should have received a copy of the MIT License along with this program.
*/

export * from './src/mapping.js';
export * from './src/adapter.js';
export * from './src/persistence.js';
export * from './src/query.model.js';
export * from './src/query.resolver.js';
export * from './src/query.js';
export * from './src/client/client.js';

export { UpdateCommand } from './src/client/command/update.js';
66 changes: 66 additions & 0 deletions packages/mongo/tests/mongo-convert.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { expect, test } from '@jest/globals';
import {
entity,
MongoId,
PrimaryKey,
ReflectionClass,
} from '@deepkit/type';
import { createDatabase } from './utils';
import { UpdateCommand } from '../src/client/command/update';

Error.stackTraceLimit = 100;

@entity.name('Model').collection('test_convert')
export class Model {
_id: MongoId & PrimaryKey = '';

a: number = 0;

constructor(public name: string) {
}
}

@entity.name('ModelString').collection('test_convert')
export class ModelString {
_id: MongoId & PrimaryKey = '';

a: string = '';

constructor(public name: string) {
}
}

// This is a use case for UpdateCommand to make a $convert query possible,
// which is not directly supported by the orm.
// Therefore UpdateCommand is exported by the mongo package.
test('raw $convert UpdateCommand', async () => {
const db = await createDatabase('testing');
await db.query(Model).deleteMany();

const item = new Model('foo');
item.a = 123;

const item2 = new Model('foo2');
item2.a = 456;

await db.persist(item);
await db.persist(item2);

expect(await db.query(Model).filter({a: 456}).has()).toBe(true);


const schema = ReflectionClass.from(Model);
const command = new UpdateCommand(
schema,
[{
// for types see: https://www.mongodb.com/docs/manual/reference/operator/aggregation/type/#available-types
// int to string
q: {a: {$type: 16}},
u: [{ $set: { a: { $convert: { input: "$a", to: 2 } } } }],
multi: true
}],
);
await db.adapter.client.execute(command);

expect(await db.query(ModelString).filter({a: '456'}).has()).toBe(true);
});

0 comments on commit 4d627d2

Please sign in to comment.