I need to update a property value of a specific document by sending a request to my NextJs API using fetch.
// Update items in state when the pending time in queue has passed, set allowed: true
items.map((item) => {
const itemDate = new Date(item.added)
const timeDiff = currentDate.getTime() - itemDate.getTime()
const dateDiff = timeDiff / (1000 * 3600 * 24)
if (dateDiff >= 7) {
const updateItem = async () => {
try {
// Data to update
const updatedItem = {
_id: item._id,
name: item.name,
price: item.price,
allowed: true
}
console.log(updatedItem)
await fetch ('/api/impulses', {
method: 'PATCH',
body: JSON.stringify(updatedItem)
})
} catch (error) {
alert('Failed to update items status')
}
}
updateItem()
}
})
The API successfully receives the data object and I can extract all necessary information from req.body
for updating the MongoDB document. However, there seems to be an issue with treating the ID (_id: ObjectId('xx1234567890xx')
) for filtering the document for updating.
Despite manipulating the format and including only essential data along with the _id, I still face challenges...
const jsonData = JSON.parse(req.body)
const { _id } = jsonData
// Fields to update
const { name, price, allowed } = jsonData
const data = {
name,
price,
allowed
}
const filter = {
_id: _id
}
const update = {
$set: data
}
const options = {
upsert: false
}
console.log("_id: ", filter) // returns { _id: 'the-correct-id-of-this-document' }
Conclusively, the update is implemented on db.collection
and responses are returned:
await db.collection('impulses').updateOne(filter, update, options)
return res.json({
message: 'Impulse updated successfully',
success: true
})
Even though the _id
matches the document id, it doesn't update. If the option upsert: true
is used, a new document is created with the same _id and updated data...
The unique aspect about the documents generated through a form submission is that the id is in this format: _id: 'xx1234567890xx'
. Thus, compared to an ID with ObjectId at the start, no conflicts arise. Despite my attempts to integrate 'ObjectId' in various ways, it appears to create a new ObjectId which no longer references the original document.
Any suggestions?