Home > Mobile >  If one of the multiple queries running one after another fails in mongoose?
If one of the multiple queries running one after another fails in mongoose?

Time:12-26

I'm developing an API, In this API I have two Models: SongModel and UserModel. When I save a new song, I also run another query to add the song._id to the user who created it. But due to my mistake in code, the second query threw an error and there was a problem, the song that was just created had no means to be updated and deleted in the future because the user had no way of identifying that song without its _id.

For now, I have fixed my code, but in the future, so that my site would not face a similar issue again, How can I handle it?

I searched different articles and questions but couldn't find any practices to counter this. Is there any method in mongoose or any package to solve this problem?

CodePudding user response:

You have to use MongoDB Transactions. With it, either everything will succeed, or nothing will.

Basically, you first have to create a session, and use that session for all you queries. After all the queries, you will commit the transaction.

To use transactions with Mongoose, you can check their official docs.

Here is the how the code can look like:

const mongoose = require('mongoose');

const addNewSong = async (req, res) => {
  const { song } = req.body;
  const user_id = req.user._id;

  // Start a session
  const session = await mongoose.startSession();

  try {
    // Start a transaction
    session.startTransaction();

    // Create new song
    const song = await Songs.create([song], { session });

    // Update user
    await Users.updateOne({ _id: user_id }, { $addToSet: { songs: song[0]._id } }, { session });

    // Commit the transaction
    await session.commitTransaction();

    return res.status(200).json({ success: true });
  } catch (error) {
    return res.status(500).json({ success: false });
  } finally {
    // End session
    session.endSession();
  }
};
  • Related