猫鼬:是否可以将多个数据库调用组合成一个?

时间:2019-12-18 05:27:12

标签: mongodb mongoose

我在1个API调用中有4个数据库操作,是否过多?可以/应该以某种方式将它们组合吗?

// 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();

感觉好像分配了数据库访问,但是也许我不确定吗?

也许3和4不需要await,我可以在2点后将响应发送到前端?

也许我想得太多了?

1 个答案:

答案 0 :(得分:1)

第一和第四操作看起来像这样可以组合:

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

或者您可以使用猫鼬Model.bulkWrite

组合3个与UserModel相关的更新