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

161
Visualizações
Patch (findByIdAndUpdate) in Mongoose

I have to do a simple CRUD in Node/Mongoose API. I also have to make put and patch and while doing patch, I'm a bit confused, because I wanted to use findByIdAndUpdate method, but as I see on examples, there is only one record updated, e.g. {name: "newName"}. I was wondering what I should do if for example I wanted to update two cells?

My schema:

const userSchema = new Schema({
    login: String,
    email: String,
    registrationDate: Date,
});

My Patch code:

router.patch('/:id', async (req, res) => {
    const id = req.params.id;
    User.findByIdAndUpdate(id, { ??? },
        function (err, docs) {
            if (err){
                console.log(err)
            }
            else{
                console.log("Updated User : ", docs);
            }
        });

});

I don't know what I should write in "???", because what if I wanted to update only the login, and what if I wanted to update name and email? Maybe I'm wrong and PATCH is used only to edit ONE cell and in other cases I should use PUT?

Edit:

I made it work using something like this:

router.patch('/:id', async (req, res) => {
    const id = req.params.id;
    let updates={}
    if (req.body.login) {
        updates["login"] = req.body.login
    }
    if (req.body.email) {
        updates["email"] = req.body.email
    }
    if (req.body.registrationDate) {
        updates["registrationDate"] = req.body.registrationDate
    }
    User.findByIdAndUpdate(id, updates,
        function (err, docs) {
            if (err){
                console.log(err)
            }
            else{
                console.log("Updated User : ", docs);
            }
        });

});

Anyway I have a question what I should do to "stop" the action. I'm using HTTPie and when I write http PATCH......, it seems like I can't write anything else, because it's still working, I need to do CTRL+C to stop the query.

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

0

Just write the fields you want to change and the new values ​​separated by commas.

const id= req.params.id;
const email = "newemail";
const date = "1991/13/01";
const user = await User.findByIdAndUpdate(
    {
      _id: id,
    },
    { email, registrationDate: date},
    { upsert: false }
  );
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