I am trying to add values inside the object id. Object id is created before but I want to add more values in the future inside the object ID.
This is my MongoDB database:
[{
label: 'colors',
options: [
{ label: 'Black', value: 1 },
{ label: 'Green', value: 2 },
]
}]
My expectation is when I will send a new object it will insert a new object inside the options property. suppose my new object is {label: ‘blue’, value: 3} it will be like this:
[{
label: 'colors',
object: [
{ label: 'Black', value: 1 },
{ label: 'Green', value: 2 },
{label: 'blue', value: 3}
]
},
I am trying this way, I am storing the previous data value, inserting a new value, and sending it to the backend. but it’s not working. is there any different way I can fix it?
const addAttributeValues = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
if (label === '') {
return
}
const slug = label?.split(' ').join('-')
const options: any = [] // previous value storing
let update; // inserting previous and new value
if (attr.options) { // checking if the previous data has options property or not
options.push(attr.options)
const length: any = options.length
update = { options: { ...options, [length]: { label, slug } }, id: attr._id }
}
else { // if option property doesn't exist it means no new value added before
update = { options: { label, slug }, id: attr._id }
}
fetch('http://localhost:5000/dashboard/attributes', {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(update)
})
.then(res => res.json())
.then(data => {
setLabel('')
setIfShouldUpdate(true)
})
}
Backend API, I use put method, I don’t know is there any other method for inserting new values in the future.
// ADD ATTRIBUTES VALUE
app.put('/dashboard/attributes/', async (req, res) => {
const { options, id } = req.body
const filter = { _id: objectId(id) }
const updateDoc = {
$set: {
options: options
},
};
const result = await unityMartAttributes.updateOne(filter, updateDoc);
res.json(result)
console.log(result);
})