-
-
Notifications
You must be signed in to change notification settings - Fork 544
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Upsert implementation #367
Comments
Just create a generic class extending Something like this should work: export class CustomBaseRepository<T extends AnyEntity<T>> extends EntityRepository<T> {
upsert() { ... }
}
Nope. Not sure if I understood well, do you also need help with implementation of the upsert method? Should be quite trivial. |
Thanks, it's perfect. No, I don't need help with the implementation but I need to understand about the internals of the EntityRepository, but for that I can check the source code. Thank you again |
Its pretty simple, all what repository does is that it forwards calls to the entity manager with the entity name stored in async upsert(data, where) {
let e = await this.findOne(where);
if (e) {
wrap(e).assign(data);
} else {
e = this.create(data);
}
await this.persistAndFlush(e); // or maybe you do not want to flush here, depends on the use case
return e;
} |
Oh, is there a way to take advantage of upsert in mongo? I know it would be specific for only one DB, but it would run in a transaction. Otherwise I don't know if multiple operations like reading/writing can happen in transaction on MongoDB. |
You can access the driver/connection and run methods on the native collection wrapper too: // @ts-ignore
const collection = (this.em as EntityManager<MongoDriver>).getConnection().getCollection(this.entityName);
await collection.findOneAndUpdate(where, updates, {upsert: true}); But looking at the code, |
Perfect, thanks! |
|
Fast and cool, thanks! |
Can we close this now? |
Yes, sure, I'm closing it |
Is your feature request related to a problem? Please describe.
A clarification on a possible feature
I'm going to create a
CustomBaseRepository
to implement a generic method to find or create (upsert). Can you point me to some example on how to create such a base repository? The documentation (https://mikro-orm.io/docs/repositories#custom-repository) si not very exhaustive and the links provided have no example for a custom base repository.Alternatively, does such method exist already?
The text was updated successfully, but these errors were encountered: