node.jsmongodbmongoose

Mongoose, updating a single element in array of numbers


i'm kinda new at develping apps with nodejs and mongoose, i'm trying to update an array of numbers by modifying a single value inside it but i can't find the correct way to do it.

this is the document:

{ 
id:5,
arrayOfValues:[2,3,4,5]
}

Let's say i receive a value of 10 that must be stored in position 1, the desired outcome is:

{ 
id:5,
arrayOfValues:[2,10,4,5]
}

I thought about using model.findOne() and then model.updateOne() but since this operation could be done several times per minute i was searching for a more efficient method.

Edit: This is my current typescript code:

const filter = {'id':receivedMessage.id};
const options = {upsert:true, includeResultMetadata: true};


const foundDocument = await myModel.findOne(filter);

if(foundDocument){
    let tempArray = foundDocument.myArray;
    let position = receivedMessage.k;
    let value = receivedMessage.v

    tempArray[position] = value

    await myModel.updateOne(filter, {myArray: tempArray}, options);
}

What is the correct way to update only that single element of the array?


Solution

  • You can simplify the update operation by directly using Mongoose updateOne method with the $set operator. Here's the simplified version of your update operation, without the need to retrieve the document first:

    const filter = { id: receivedMessage.id };
    await myModel.updateOne(
      filter,
      { $set: { [`arrayOfValues.${receivedMessage.k}`]: receivedMessage.v } }
    );