Reputation: 1
I have used find()
to fetch a record which was giving me a mongoose record, then I used toJson()
to convert to an object so that I can modify the fields.
body = req.body;
const data = model.find({target: body.target});
I am getting a mongoose document with fields like this:
['$__', 'isNew', 'errors', '$locals', '$op', '_doc', '$init' ]
So I converted the object to a plain object by using the toJSON()
method:
const Obj = data[0].toJSON();
Now I am creating an 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 recognising the fields, is it because I converted to JSON and updating it? If not please let me know where I made a mistake.
Upvotes: -1
Views: 98
Reputation: 11
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 });
Upvotes: 0
Reputation: 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 the console, shows that your connection to the database is correct, and it's working fine, it's just not fast enough to be executed before 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})
}
Upvotes: 0