3

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

3
  • The issue may be your client calling the endpoint. Log your backend values, and post your client code. Jan 8, 2022 at 11:10
  • With the set function I am getting an error that path id is not defined Jan 9, 2022 at 7:09
  • see suggestion to use _id instead of id Jan 9, 2022 at 19:01

3 Answers 3

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);
        }
    });
2
  • great ! for other people seeing this, replace hard coded values with dynamic variables. Thanks Jan 18, 2022 at 15:41
  • update is depreciated for version greater than 6.1.7 , hence we are using updateOne with better query parameters. Jan 18, 2022 at 15:44
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/

1
  • $set will update the element attribute for the matching index. Looks good to me. Jan 8, 2022 at 11:09
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"}) {
15
  • please check the edited error part.. Jan 10, 2022 at 6:23
  • please post an example of your full document, including the id field. Jan 10, 2022 at 12:19
  • ok i'll do that Jan 10, 2022 at 12:27
  • apart from that the id coming to the controller is '5eb985d440bd2155e4d788e2' which also seems a problem as the find by id is not able to understand it as object id Jan 10, 2022 at 12:28
  • i looked at your data source and will add another suggestion. Jan 10, 2022 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.