Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
Finding record by recordId and userId while updating a value inside array, using Mongose

I'm sorry if the title is a bit confusing, but I'm not sure how to re-phrase it.

So I have the following object:

{
    "_id": "622dec2e037d7ae286b366c9",
    "name": "Moriel Odeski",
    "email": "moriel96@gmail.com",
    "street": "Ben Gurion",
    "city": "Be'er Sheva",
    "zipcode": 329886,
    "tasks": [
        {
            "id": "1",
            "title": "Test",
            "completed": true
        },
        {
            "id": "2",
            "title": "Test2",
            "completed": false
        },
        {
            "id": "3",
            "title": "Test3",
            "completed": false
        },
        {
            "id": "4",
            "title": "Do The Dishes",
            "completed": false
        }
    ],
    "posts": [
        {
            "id": 1,
            "title": "That's Moriel's Post",
            "body": "According to my evaluations 0-0"
        },
        {
            "id": 2,
            "title": "Something about something",
            "body": "That's interesting"
        }
    ]
}

I'm trying to write a function that gets a userID and a taskID and by calling it, it changes the .completed of the task to true where id = taskID and where userId : userID

I have the following function that doesn't work:

const markTaskCompleted = (userID , taskID) =>
{
    return new Promise((resolve, reject) =>
    {
        User.findOneAndUpdate({id : userID , tasks : {$elemMatch: {id : taskID}}},
            {$set: {"tasks.$.completed" : true}},
            {"new" : true , "safe" : true , "upsert" : true} , function(err , data)
            {
                if(err){reject(err)}
                else
                {
                    resolve(data.tasks)
                }
            })
    })
}

It throws :

Plan executor error during findAndModify :: caused by :: The positional operator did not find the match needed from the query.

Where did I go wrong with this?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I feel difficult to read your code because it doesn't look clean.. so maybe first it's better to make it cleaner.. I guess?

const markTaskCompleted = async (userID , taskID) => await User.findOneAndUpdate({
    id: userID, 
    tasks: {$elemMatch: {id: taskID}}
  },
  {$set: {"tasks.$.completed": true}},
  {"new": true , "safe": true , "upsert": true}, 
})

You used callback inside callback so it didn't look clean to me. I used async/await. I hope this looks cleaner to you too.

The official mongoose document also uses await for findOneAndUpdate() method. https://mongoosejs.com/docs/tutorials/findoneandupdate.html#getting-started

Check it out. Can you check if the code I wrote works?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda