0

As I declare an array in the model

@Prop({ type: [Types.ObjectId], default: [] })
  for_users_ids: Types.ObjectId[];

As I want here to send a socket event to all the users of this notification, but I receive the for_users_ids as an object here

async update_read_status(_id: string, is_read: boolean, user: PayloadUser) {
    try {
      const result = await this.notification.findOne({ _id: new Types.ObjectId(_id), for_users_ids: user._id });

      if (!result) throw new NotFoundException(`Notification Not Found.`);

      result.is_read = is_read;

      await result.save();
      console.log("RESULT: ",result);
      
      const target_users = result.for_users_ids?.filter((user_id) => !user_id.equals(user._id));
      console.log('target_users: ', typeof result.for_users_ids);
      const target_user_ids_as_strings = target_users?.map((user_id) => user_id.toString());

      this.notificationGateway.emit_read_notification_for_unread_users(target_user_ids_as_strings, result._id);

      return { message: 'Notification has been updated successfully', data: result };
    } catch (error) {
      this.logger.error(error);
      throw error;
    }
  }

but I recieved error while doing this

TypeError: for_users_ids is not iterable
    at NotificationService.emit_and_mark_notifications_as_read 

1 Answer 1

-1
async update_read_status(_id: string, is_read: boolean, user: PayloadUser) {
    try {
      const result = await this.notification.findOne({
        _id: new Types.ObjectId(_id)
      });

      if (!result) throw new NotFoundException(`Notification Not Found.`);

      result.is_read = is_read;
      await result.save();
      console.log("RESULT: ", result);
      
      // Ensure for_users_ids is treated as an array
      let target_users: Types.ObjectId[] = [];
      if (Array.isArray(result.for_users_ids)) {
        target_users = result.for_users_ids.filter(user_id => !user_id.equals(user._id));
      } else {
        console.warn("for_users_ids is not an array:", result.for_users_ids);
        // If for_users_ids is not an array, you might want to handle this case, 
        // possibly by converting it to an array or throwing an error.
        target_users = [result.for_users_ids].filter(user_id => !user_id.equals(user._id));
      }
      
      console.log('target_users: ', typeof target_users);
      const target_user_ids_as_strings = target_users.map(user_id => user_id.toString());

      this.notificationGateway.emit_read_notification_for_unread_users(target_user_ids_as_strings, result._id);

      return { message: 'Notification has been updated successfully', data: result };
    } catch (error) {
      this.logger.error(error);
      throw error;
    }
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.