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

938
Visualizações
Node JS Mongoose update query inside for or foreach loop, is it possible?

I have 2 different objects inside an array, and i want to use those objects to update a collection in my mongodb So i though about using something like this:

for (i = 0 ; i < array.length ; i++) {
Model.update({array[i]._id},{$set : {'credits_pending' : array[i].credits_pending}},false,true)
}

But it only updates the first value of my array, i mean, array[0]

Why?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

For one thing, update (and most other operations) in Mongoose is asynchronous so you need to wait till the operation is done before continuing. It's usually better to do one operation at a time on the same collection. With the for loop, you're running two asynchronous operations at the same time on the same collection, which might give an undesired behavior.

Second, I think your Model.update() arguments are slightly off.

I like to use async.js when working with Mongoose, so below is an example on how you can update an array of objects one at a time.

var async = require('async');

async.eachSeries(array, function updateObject (obj, done) {
    // Model.update(condition, doc, callback)
    Model.update({ _id: obj._id }, { $set : { credits_pending: obj.credits_pending }}, done);
}, function allDone (err) {
    // this will be called when all the updates are done or an error occurred during the iteration
});
about 4 years ago · Santiago Trujillo Relatório

0

I don't know how your schema looks like but if that is the only way to do that, try something like -

//array - your original array
        async.eachSeries(array, function(rec, callback) {
             updateRecord(rec._id, rec.credits_pending)
                  .then((updated) => {
                      callback();
                    })
        }, function(err){
          //execution comes here when array is fully iterated.
        });

    function updateRecord(id, credits) {
    return Model.update({array[i]._id},{$set : {'credits_pending' : array[i].credits_pending}});
    }  

Mongoose internally supports promise so you don't have to worry about anything else.
"Note" - For updating multiple documents you should select some property that is common to all the documents. This approach is not correct and you should design your schema to avoid such scenarios. This answer is in the case you don't have any other choice.

about 4 years ago · Santiago Trujillo 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