Estoy tratando de agregar valores dentro de la identificación del objeto. La identificación del objeto se creó antes, pero quiero agregar más valores en el futuro dentro de la identificación del objeto.
Esta es mi base de datos MongoDB:
[{ label: 'colors', options: [ { label: 'Black', value: 1 }, { label: 'Green', value: 2 }, ] }]Mi expectativa es que cuando envíe un nuevo objeto, insertará un nuevo objeto dentro de la propiedad de opciones. supongamos que mi nuevo objeto es {label: 'blue', value: 3} será así:
[{ label: 'colors', object: [ { label: 'Black', value: 1 }, { label: 'Green', value: 2 }, {label: 'blue', value: 3} ] },Estoy intentando de esta manera, estoy almacenando el valor de datos anterior, insertando un nuevo valor y enviándolo al backend. pero no funciona. ¿Hay alguna forma diferente de solucionarlo?
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) }) }API backend, uso el método put, no sé si hay algún otro método para insertar nuevos valores en el futuro.
// 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); })