Sindbad~EG File Manager

Current Path : /home/infinitibizsol/.trash/middlewares.7/
Upload File :
Current File : /home/infinitibizsol/.trash/middlewares.7/syncModelFields.js

import db from "../model/index";

const syncModelFields = async (req, res, next) => {
  try {
    // Fetch all users
    const users = await db.User.find({});

    // Create a map to check which users already have social media entries
    const userMap = new Map(users.map((user) => [user._id.toString(), false]));

    // Check existing SocialMedia entries and update the map
    const socialMedias = await db.SocialMedia.find({});

    socialMedias.forEach((socialMedia) => {
      if (socialMedia.user_id) {
        userMap.set(socialMedia.user_id.toString(), true);
      }
    });

    // For each user in the map that doesn't have a social media entry, create one
    const newSocialMediaEntries = [];

    for (const [userId, exists] of userMap.entries()) {
      if (!exists) {
        newSocialMediaEntries.push(
          new db.SocialMedia({
            facebook: "",
            twitter: "",
            linkedin: "",
            other: "",
            sms: "",
            rss_feed1: "",
            rss_feed2: "",
            pages: [],
            user_id: userId,
            deleted: false,
          }).save()
        );
      }
    }

    // Wait for all entries to be created
    await Promise.all(newSocialMediaEntries)
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.log(error.message);
      });

    // Proceed to the next middleware or route handler
    next();
  } catch (err) {
    console.error(err.message);
    res.status(500).send({ message: "Internal server error" });
  }
};

export default syncModelFields;

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists