skip to Main Content

Given this update statement

const result = await Post.updateOne({_id: postId},{
            $pull: {reacts: {publisher: req.query.publisher}},
            $inc: {postPoints: - reactsEnum[ReactType]}
});

I want to get the react Type of the react pulled from the array in the $pull operation. is it possible to do so or to do something similar?

2

Answers


  1. Yes, here is the example: 
    
        let arrayIndex = -1; // Initialize a variable to store the index
    
    db.collectionName.find({ /* Your query criteria */ }).forEach(function(doc) {
        arrayIndex = doc.yourArray.indexOf('element-to-find');
        if (arrayIndex !== -1) {
            return; // Exit the loop once the element is found
        }
    });
    
    if (arrayIndex === -1) {
        // Element not found in any document
        // Handle this case as needed
    }
    db.collectionName.update(
        { /* Your query criteria */ },
        { $set: { [`yourArray.${arrayIndex}`]: 'new-value' } }
    );
    
    Login or Signup to reply.
  2. In MongoDB, directly getting the index of a specific element in an array while performing an update with $pull is not supported in a single operation. To achieve this, you would need to first fetch the original document, find the index of the element you want to remove in the array, and then perform the update with $pull. This requires multiple database operations.

    Code:

    // Find the document and get the array before the update
    const originalDocument = await Post.findOne({_id: postId});
    const reactsArray = originalDocument.reacts;
    
    // Perform the $pull operation
    const result = await Post.updateOne({_id: postId}, {
      $pull: {reacts: {publisher: req.query.publisher}},
      $inc: {postPoints: -reactsEnum[ReactType]}
    });
    
    // Calculate the index of the removed react by comparing the arrays
    const removedReact = reactsArray.find(react => react.publisher === req.query.publisher);
    const removedIndex = reactsArray.indexOf(removedReact);
    
    // Now you have the removed react and its index
    console.log('Removed React:', removedReact);
    console.log('Removed Index:', removedIndex);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search