Home > Enterprise >  when using async/await with mongoose i get an error
when using async/await with mongoose i get an error

Time:02-24

I want to get an ObjectId from my mongo database, but with async / await, i get an error:

ERROR [ExceptionsHandler] Query was already executed: Role.findOne({ name: { '$in': [ 'admin' ] } }) MongooseError: Query was already executed: Role.findOne({ name: { '$in': [ 'admin' ] } })

I want to call mongoose asynchronously because my userRoles array is empty when i want to use it after this code block;

here's the code role.guard.ts

  [...]
  async canActivate(context: ExecutionContext): Promise<boolean> {
    const userRoles: string[] = [];
    let accessRoleId = '';

    let isAuthorized = false;
    const accessRole = this.reflector.get<string[]>('roles', context.getHandler());
    if (!accessRole) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const user = request.user;

    for (let i = 0; i < user.roles.length; i  ) {
      const role: string = user.roles[i]
      userRoles.push(role);
    }

    const findId = await this.RoleModel.findOne({ 'name': accessRole }
    , (err, role) => {
    if (err){
        console.log(err);
    }
    else {
        console.log('role ->', role._id.valueOf()); // role -> 621268634b936e81528bc220
        accessRoleId = role._id.valueOf();
    }
  });

  [...]

}

Any idea? Thanks!

CodePudding user response:

You either use callbacks or promises.

Callbacks:

 const findId = this.RoleModel.findOne({ 'name': accessRole }
    , (err, role) => {
    if (err){
        console.log(err);
    }
    else {
        console.log('role ->', role._id.valueOf()); // role -> 621268634b936e81528bc220
        accessRoleId = role._id.valueOf();
    }

Promises:

 try {
     const role = await this.RoleModel.findOne({ 'name': accessRole });
     console.log('role ->', role._id.valueOf()); // role -> 621268634b936e81528bc220
     accessRoleId = role._id.valueOf();
 } catch(err) {
     console.log(err);          
 }
  • Related