Bill
Bill

Reputation: 5150

Mongoose: is it possible to combine many database calls into one?

I've got 4 database operations in 1 API call, is it excessive? Can/should they be combined somehow?

// 1) Get the id for the user I want to follow

      const account = await userModel
        .findOne({ 'shared.username': username })
        .exec();
      if (!account) throw new Error('User not found');

// 2) Save the user id I want to follow and my Id into the following collection

      const followed = new followingModel({
        followingId: account.id,
        userId: id,
      } as FollowingModelInterface);
      const saved = await followed.save();

// 3) Increment the number of people I'm following

      const addFollowing = await userModel
      .findOneAndUpdate(
        { _id: id },
        {
          $inc: { 'shared.following': 1 },
        },
        {
          new: true,
        }
      )
      .exec();

// 4) Increment the number of people who are following the user i just followed

      const addFoller = await userModel
      .findOneAndUpdate(
        { _id: account.id },
        {
          $inc: { 'shared.followers': 1 },
        },
        {
          new: true,
        }
      )
      .exec();

It feels like allot of trips to the database but maybe it's ok I'm not sure?

Maybe 3 and 4 dont need await and I can send a response to the front end after 2??

Maybe I'm overthinking it??

Upvotes: 1

Views: 99

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

First and fourth operations look like that can be combined like this:

  const account = await userModel.findOneAndUpdate(
    { "shared.username": username },
    {
      $inc: { "shared.followers": 1 }
    },
    { new: true }
  );

Or you can combine 3 userModel related update by using mongoose Model.bulkWrite

Upvotes: 1

Related Questions