1

Hello everybody i have this bad code for me how i can optimize it ?

If i used SQL i can do used inner Queries in one query...

"User" it's only object from mongoose

  getProfile: async (req, res) => {
        const { id } = req.params;

        try {
            const {
                image,
                name,
                gender,
                about,
                email,
                phone,
                address
            } = await User.findById({ _id: id }).select('image name gender about email phone address');

            const subscriptions = await Subscriber.countDocuments({ userId: id });
            const subscribers   = await Subscriber.countDocuments({ subscriberId: id });

            const user = {
                image,
                name,
                gender,
                subscriptions,
                subscribers,
                about,
                email,
                phone,
                address
            };

            res.json(user);

        } catch (err) {
            console.log(err);
        }

    }

PS. I only study with this technologies

If i used spread operator of result of my query from User i have like this: enter image description here

And that what i have in result

module.exports = {

    getProfile: async (req, res) => {
        const { id } = req.params;

        try {

            const [data, subscriptions, subscribers] = await Promise.all([
                User.findById( { _id: id },
                    {
                        __v: false,
                        password: false,
                        date: false,
                        _id: false
                    },
                ),
                Subscriber.countDocuments({ userId: id }),
                Subscriber.countDocuments({ subscriberId: id })
            ])

            const user = {
                ...data._doc,
                subscriptions,
                subscribers
            }

            res.json(user);

        } catch (err) {
            console.log(err);
        }

    }


Richard
  • 101
  • 7

2 Answers2

1

You can embed subscriptions [array of documents] in the User model. But bear in mind that could put limitations on your api, if subscriptions might be accessed regardless of its user.

Mu-Majid
  • 851
  • 1
  • 9
  • 16
  • Can u please give me link where i can read about this? Or link with examples .. – Richard Jan 21 '20 at 13:29
  • There are a lot of books talking about NoSql DBs, I recommend you have a look at this one at first : https://martinfowler.com/books/nosql.html, Read chapter 2 about how to aggregate data and deal with it as a unit. – Mu-Majid Jan 21 '20 at 15:08
  • Thanks for answer) – Richard Jan 21 '20 at 18:58
1

Since all of your queries are independent, the best we can do is execute all of them parallelly with Promise.all(). Try something like this:

getProfile: async (req, res) => {
    const { id = _id } = req.params;
    try {
        const getUser = User.findById({ _id }).select('image name gender about email phone address');
        const getSubscriptions = Subscriber.countDocuments({ userId: id });
        const getSubscriber = Subscriber.countDocuments({ subscriberId: id });

        const [userData, subscriptions, subscribers] = await Promise.all([getUser, getSubscriptions, getSubscriber]);
        const user = {
            ...userData,
            subscriptions,
            subscribers,
        };
        res.json(user);
    } catch (err) {
        console.log(err);
    }
}

Hope this helps :)

Mohammed Amir Ansari
  • 2,311
  • 2
  • 12
  • 26
  • Thanks, I will try to do it ... :) – Richard Jan 21 '20 at 13:42
  • Your solution almost help me but one issue when i use a spread operator with userData.. I attached a picture in my question above – Richard Jan 21 '20 at 19:15
  • Glad it helps, for the other problem you mentioned, try changing **...userData** to **...userData.toObject()** If you wants to know whats actually happening there, take a look on [this](https://stackoverflow.com/questions/59475327/mongoosejs-find-returning-whole-model-instead-of-document/59475644#59475644) – Mohammed Amir Ansari Jan 22 '20 at 05:39