-
-
Notifications
You must be signed in to change notification settings - Fork 611
Closed
Labels
wontfixThis will not be worked onThis will not be worked on
Description
Describe the bug
Imagine a simple User entity with just id and username fields.
We need to save a bunch of users using Promise.all().
The
userstable should be empty before running the script below.
The script:
async run() {
const users = [
{ username: 'A' },
{ username: 'B' },
{ username: 'C' },
{ username: 'D' },
];
await Promise.all(users.map(async (userData) => this.saveUser(userData)));
}
async saveUser({ username }): Promise<User> {
const userRepo = getEntityManager().getRepository(User);
// This query is required. We need another 'await' before 'persistAndFlush' to trigger the bug.
let user = await userRepo.findOne({ username });
if (!user) {
user = new User();
user.username = username;
await userRepo.persistAndFlush(user);
}
console.log('User ID:', user.id);
return user;
}
Console output:
[query] select "u0".* from "users" as "u0" where "u0"."username" = 'A' limit 1 [took 7 ms]
[query] select "u0".* from "users" as "u0" where "u0"."username" = 'C' limit 1 [took 13 ms]
[query] select "u0".* from "users" as "u0" where "u0"."username" = 'B' limit 1 [took 14 ms]
[query] begin
[query] select "u0".* from "users" as "u0" where "u0"."username" = 'D' limit 1 [took 47 ms]
[query] insert into "users" ("created_at", "updated_at", "username") values ('2022-03-21T13:23:01.398Z', '2022-03-21T13:23:01.398Z', 'A') returning "id", "created_at", "updated_at" [took 4 ms]
[query] commit
User ID: undefined
User ID: undefined
User ID: undefined
User ID: 1
And in the database we have only 1 user created (user A).
But everything works fine if we remove this line:
let user = await userRepo.findOne({ username });
Versions
| Dependency | Version |
|---|---|
| node | 16.13.2 |
| typescript | - |
| mikro-orm | 5.1.1 |
| your-driver | postgres |
Metadata
Metadata
Assignees
Labels
wontfixThis will not be worked onThis will not be worked on