Update value in document array without deleting other values

I want to update one value when a file is downloaded in an array in a document in MongoDB. For some reason it updates it but also deletes every other value of the object in the array. Does anyone know how to work around this issue?

My model looks like this:

    token: {
        type: String,
        required: true
    },
    apiKey: {
        type: String,
        required: true
    },
    documents: [
        {
        filename: {type: String, required: true },
        id: {type: String, required: true},
        fileDownloaded: {type: Boolean, required: true}
        }
    ],
})

I want to change fileDownloaded to true when its downloaded, so i tried runnin this after the download function:

const files = await File.findOneAndUpdate({
    "documents.id": "id here2"
}, {
    "documents": [{
        "fileDownloaded": "true"
    }]
}, {
    useFindAndModify: false
})

However when it updates fileDownloaded to true, it also deletes the filename and id value

Answer

You have to use positional operator $ like this:

In this way you are telling mongo: “Look for a document where the id is id here2 and then update the document found (using positional operator $) and set value fileDownloaded to true“.

await File.findOneAndUpdate({
  "documents.id": "id here2"
},
{
  "$set": {
    "documents.$.fileDownloaded": true
  }
},
{useFindAndModify: false})

Example here