Skip to content Skip to sidebar Skip to footer

Mongoose: How To Update An Existing Element In Array?

I was wondering if there is a better way to update an existing element in an array instead of fetching database three times. If you have any ideas I would appreciate it. Thank you!

Solution 1:

Well, if you don't need to return the updated document, Please try this one - this will just return a write result, with this things can be achieved in one DB call :

const creatStock = async (symbol, webApiData) => {
    try {
        // reversed arrayconst webApiDataReversed = webApiData.reverse();
        const query = { symbol };

        awaitStock.bulkWrite([
            {
                updateOne:
                {
                    "filter": query,
                    "update": { $pop: { data: 1 } }
                }
            }, {
                updateOne:
                {
                    "filter": query,
                    "update": {
                        $addToSet: {
                            data: webApiDataReversed
                        }
                    }
                }
            }
        ])
    } catch (ex) {
        console.log(`creatStock error: ${ex}`.red);
    }
};

Ref :mongoDB bulkWrite

Solution 2:

you can do like this way :

const creatStock = async (symbol, webApiData) => {
  try {
    // reversed arrayconst webApiDataReversed = webApiData.reverse();

    const query = { symbol };

    let stock =  awaitStock.findOne(query);
    if(stock){
       let stockData = JSON.parse(JSON.stringify(stock.data));
       if(stockData.length>0){
          stockData.pop(); 
       }
       stockData.concat(webApiDataReversed);
       stock.data = stockData;
       await stock.save();
    }
  } catch (ex) {
      console.log(`creatStock error: ${ex}`.red);
  }

Post a Comment for "Mongoose: How To Update An Existing Element In Array?"