I can't figure this out. I have an object in an array within another object which I need to update with mongoDB updateOne.
I make the call, it says it found it OK and has updated it ({ n: 1, nModified: 1, ok: 1 }). But then on checking no update is made in the database...
What am I doing wrong here?
Model
const pathwayDetailsSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
associatedPathwayID: {
type: mongoose.Schema.Types.ObjectId,
required: true
},
pages: [
{
_id: { type: String },
x: {
type: Number,
required: true
},
y: {
type: Number,
required: true
},
widgets: [
{
more nested objects..
}
]
}
]
}
Router call
router.post('/pageupdate/',auth, async(req,res)=>{
const pageID = req.body.pageID; //Page ID string
const pathwayID = req.body.pathwayID; // pathwayID string
const update = req.body.update; //{x: new X value, y: new Y value}
try{
console.log("receieved: ",pageID, pathwayID, update);
let updatedDoc = await PathwayDetails.updateOne(
{ associatedPathwayID: pathwayID, "pages._id": pageID },
{ $set: update}
);
console.log("successful? ",updatedDoc)
res.status(201).send(updatedDoc)
}
catch(e){
etc...
}
});
Changing x and y passes through fine and it says it updates. But on checking the database no change is made...
CodePudding user response:
I think you have missed async
keyword before await
.
A function should be an async
inorder to use the await
keyword.
So, you wrap the code inside a async
function.
Since you are not using the async function, await has lost it's functionality, so it's basically updating the old value again and again. It's not awaiting fo the new value. So you are not seeing any change in the value in the database even though the code is executed successfully.
Try the below code:
const update_document = async (req, res) => {
let updatedDoc = await PathwayDetails.updateOne(
{ associatedPathwayID: pathwayID, "pages._id": pageID },
{ $set: update}
);
res.status(201).send(updatedDoc)
};
After this call the update_document
function with the router.
I think this will work.
CodePudding user response:
Figured it out.
The update I was passing wasn't pointing to a nested object correctly.
Rather than update being {x: new X value, y: new Y value}
needed to pass a nested update it must be {"pages.$.x": new X value, "pages.$.y": new Y value}
It is annoying that mongo returns a response saying it has updated the database when it can't find the field to update!