skip to Main Content

I have used find to fetch record which was giving me a mongoose record, then I used toJson() to convert to object so I can modify the fields.

body = req.body;

const data = model.find({target: body.target});

I am getting mongoose documnet with fields like this…. [‘$__’, ‘isNew’, ‘errors’, ‘$locals’, ‘$op’, ‘_doc’, ‘$init’ ]

so I conveted the object to plain object by using toJSON() method

const Obj = data[0].toJSON();

now I am creating a update object to set…

const updateObj = {
[body[str]] = parseFloat(Obj[num_1]) + parseFloat(body[num_1])

}

model.findOneAndUpdate({target: body.target},{
$set:updateObj

}

this is my code structure, I am unable to update fields, but in console the data is coming properly, thanks in advance

I am getting the correct result in console but mongodb is not recognizing the fields, is it because I converted to JSON and updating it?, if not please let me know where I did mistake

2

Answers


  1. If you are using mongodb atlas,
    Then the problem here might be related to the way you are collecting data coming from database.

    The fact that the data is logged correctly in th console, shows that your connection to the database is correct, and it’s working fine, it’s just not fast enough to be executed befor your script ends. (It might be visible in the Network tab)

    Fetching data from the database needs to be an asynchronous function, since it takes some time to get the data from the hosted database,
    So you need to use async/await keywords to ensure that your mongodb query returns a promise.

    As for example,

        async getData(){
    const data = await model.find({target: body.target})
    }
    
    Login or Signup to reply.
  2. const data = await model.find({ target: body.target });
    

    const Obj = data[0].toJSON();
    const updateObj = { [body[str]]: parseFloat(Obj[num_1]) + parseFloat(body[num_1]) };
    await model.findOneAndUpdate({ target: body.target }, { $set: updateObj });

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search