OneCompiler

blog code

135

To convert the given Sequelize code for fetching user details from a relational database to MongoDB, you'll need to use MongoDB queries and change the structure of the code to fit MongoDB's document-oriented model. Here's a basic conversion:

const { isValid } = require('date-fns');
const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;

const UserDetailModel = require('./models/UserDetail');  // Assuming you have a UserDetail model defined

exports.getUsersUploadList = async (req, res) => {
  try {
    const limit = req?.body?.limit || 10;
    const page = req?.body?.page || 1;
    const skip = (page - 1) * limit;

    let estatus = req?.body?.filter?.send_email_status === "active" ? 1 : 0;
    let matchConditions = {};

    if (req?.body?.filter) {
      const startDate = new Date(req.body?.filter?.startDate + "T00:00:00");
      const endDate = new Date(req.body?.filter?.endDate + "T23:59:59");

      if ((startDate && isValid(startDate) && endDate && isValid(endDate) && startDate <= endDate) || req.body.filter.send_email_status) {
        matchConditions = {};

        if (startDate && endDate) {
          matchConditions.updatedAt = { $gte: startDate, $lte: endDate };
        }

        if (req.body.filter.send_email_status) {
          matchConditions.send_email_status = estatus;
        }
      }
    }

    let users = [];
    let totalCount = 0;

    if (req.userData && req.userData.user_type === "super_admin") {
      const aggregationPipeline = [
        { 
          $match: matchConditions
        },
        {
          $lookup: {
            from: "users",
            localField: "user_id",
            foreignField: "_id",
            as: "user"
          }
        },
        {
          $unwind: "$user"
        },
        {
          $lookup: {
            from: "businesses",
            localField: "user._id",
            foreignField: "created_by",
            as: "business"
          }
        },
        {
          $lookup: {
            from: "login_logs",
            localField: "user._id",
            foreignField: "user_id",
            as: "login_log"
          }
        },
        {
          $addFields: {
            leadstatus: {
              $cond: {
                if: { $ne: ["$login_log", []] },
                then: "hot",
                else: "new"
              }
            }
          }
        },
        {
          $project: {
            user_id: "$user._id",
            mobile_number: "$mobile_number",
            city: "$city",
            state: "$state",
            country: "$country",
            pincode: "$pincode",
            web_address: "$web_address",
            address: "$address",
            other_details: "$other_details",
            send_email_status: "$send_email_status",
            createdAt: "$createdAt",
            updatedAt: "$updatedAt",
            users_id: "$user._id",
            email: "$user.email",
            name: "$user.name",
            slug: "$business.slug",
            leadstatus: 1
          }
        },
        {
          $sort: { "users_id": -1 }
        },
        {
          $skip: skip
        },
        {
          $limit: limit
        }
      ];

      users = await UserDetailModel.aggregate(aggregationPipeline);
      totalCount = await UserDetailModel.countDocuments(matchConditions);
    }

    return res.status(200).json({
      success: true,
      totalCount,
      message: "UserDetails list fetched successfully",
      result: users,
    });
  } catch (err) {
    console.log(err, "Error");
    return res.status(500).json({
      success: false,
      message: "Something went wrong.",
      err: err.message,
    });
  }
};

This conversion assumes that you have defined a Mongoose model for UserDetail and have a connection to your MongoDB database. Also, the aggregation pipeline is used to perform the required joins and lookups similar to SQL joins in the original Sequelize code. Adjust the code based on your actual MongoDB schema and model definitions.