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

351
Visualizações
How Do I Update An Object in Mongoose?

I have been facing some problem while updating the data in the db using mongoose, Therefore thanks in advance for the help.

I have been sending some data from a dynamic form that contains different set of fields each time... but when i update the array in the db it changes those fields.

This was my controller function earlier:-

exports.savePageContent = (req, res, next) => {
    const id = req.body.dest;  // getting page data document id
    delete req.body.dest;
    var arr = [];

    // When we are returning the same page each time after we submit the data for the particuklar section form then how are we supposed to redirect the user to next page once he is done doing all 

    var fieldKeys = Object.keys(req.body);
    for(let i = 0; i < fieldKeys.length; i++)
    {
        arr.push({fieldRef : fieldKeys[i], fieldValue : req.body[fieldKeys[i]]});
    }

    pageDataModel.findByIdAndUpdate(id, {pageData : arr}).exec(function(err, result) {
        if(err){
            console.log(err);
        }
        else { 
            console.log("data is inserted");
            req.flash('message', "Data Saved Successfully");
            
        }
    })

} 

I also tried a few updates and then moved to this portion

This is my new controller function :

exports.savePageContent = (req, res, next) => {
    const pageid = req.body.dest;  // getting page data document id
    delete req.body.dest;

    var fieldRefData = "";
    var fieldValueData = "";

    var fieldKeys = Object.keys(req.body);
    for(let i = 0; i < fieldKeys.length; i++)
    {
        fieldRefData = fieldKeys[i];
        fieldValueData = req.body[fieldKeys[i]];

       try{

        pageDataModel.update({id : pageid, "pageData.fieldRef" : fieldRefData}, {$set : {"pageData.$.fieldValue" : fieldValueData }}, {upsert : true}).exec(function(err, result) {
            if(err){
                console.log(err);
            }
            else { 
                console.log("data is inserted", result);
            }
        });

        req.flash('message', "Data Saved Successfully");

       }catch(e){
        console.log(e);
        req.flash('message', "error Occurred updating Data ");

       }
    }

    

}  

To elaborate the case for better understanding:-

This is the data that comes first time in the body

[
  { fieldRef: 'sec1.1.h1', fieldValue: 'this is the field value 1' },
  { fieldRef: 'sec1.1.p', fieldValue: 'this is the field value 1' },
  { fieldRef: 'sec1.1.a', fieldValue: 'this is the field value 1' },
  { fieldRef: 'sec1.2.h2', fieldValue: 'this is the field value 1' }
]

and This is the data that comes the second time :-

[
  { fieldRef: 'sec2.1.h1', fieldValue: 'this the field value 2' },
  { fieldRef: 'sec2.1.p', fieldValue: 'this the field value 2' },
  { fieldRef: 'sec2.1.a', fieldValue: 'this the field value 2' },
  { fieldRef: 'sec2.2.h1', fieldValue: 'this the field value 2' }
]

when i want both the data's in the db but when i send one the second data the first one gets updated to the second one and vice versa..

this is the db images of the scenario

this is the data in the document on the first operation

this is the data in the document on the second operation

i am not able to keep and update them both... so please help me ...

This is the error that I am getting most of the time which says that the query is wrong

MongoServerError: The positional operator did not find the match needed from the query.
    at /home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/operations/update.js:80:33
    at /home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/connection_pool.js:272:25
    at handleOperationResult (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/sdam/server.js:370:9)
    at MessageStream.messageHandler (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/connection.js:479:9)
    at MessageStream.emit (events.js:400:28)
    at processIncomingData (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/message_stream.js:108:16)
    at MessageStream._write (/home/pushkar/Desktop/NodejsWebApp1/node_modules/mongodb/lib/cmap/message_stream.js:28:9)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at Socket.ondata (internal/streams/readable.js:731:22) {
  index: 0,
  code: 2
}

Also if I was unable to make my scenario clear please leave a comment and I will try to explain it more clearly.. thanks In Advance

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

$set will replace a new value for the key. If you use the 3rd value then the $set will replace the 3rd value, use $push instead of $set operator.https://docs.mongodb.com/manual/reference/operator/update/push/

over 4 years ago · Santiago Trujillo Relatório

0

Try using _id instead of id.

pageDataModel.update({_id : pageid, "pageData.fieldRef"}) {

Or even pageData._id instead of id.

pageDataModel.update({'pageData._id' : pageid, "pageData.fieldRef"}) {

Furthermore, your id is a string in the query, but an object id in database, so call a helper.

pageDataModel.update({'pageData._id' : mongoose.Types.ObjectId(pageid), "pageData.fieldRef"}) {
over 4 years ago · Santiago Trujillo Relatório

0

I hope this should solve the issue :

pageDataModel.updateOne({_id : "61d73f31cb5681b85618995a", "pageData.fieldRef" : "sec2.c" },{"$set" : {"pageData.$.fieldValue" : "Mkc" }}).exec(function(err, result) {
        if(err) throw err;
        else {
            console.log(result);
        }
    });
over 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