Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

102
Views
¿Cómo puedo guardar varios elementos en mongodb?

Entonces, tengo una aplicación de comercio electrónico que, para un producto, quiero que los clientes publiquen diferentes variantes del producto con la cantidad y el precio de la variante. Luego, al guardar, quiero que el producto se guarde según la cantidad de variantes.

Por ejemplo, si hay 3 variantes del producto, el producto debe guardarse 3 veces con el mismo nombre y descripción, pero cada guardado tendrá una sola variante.

Esto es lo que he hecho.

 const [values, setValues] = useState([]) function addItem(e) { e.preventDefault() setValues([...values, { quantity, weight, price }]) setQuantity('') setWeight('') setPrice('') } <input type='text' placeholder='Product Name*' value={productName} onChange={(e) => setProductName(e.target.value)} /> <div className='form-group'> <input type='number' placeholder='Quantity' value={quantity} name={quantity} onChange={(e) => setQuantity(e.target.value)} /> <input type='number' placeholder='Weight (kg)' value={weight} name={weight} onChange={(e) => setWeight(e.target.value)} /> <input type='number' placeholder='Price' value={price} name={price} onChange={(e) => setPrice(e.target.value)} /> <button onClick={addItem}>Add</button> </div>

Al hacer clic, el elemento se agrega a un estado. Luego onSubmit, trato de recorrer el estado

 for (let i = 0; i < values.length; i++) { const res = await createProduct({ productName, price: price[i], quantity: quantity[i], weight: weight[i], }) console.log(res) }

no funciona

Aquí está el controlador expreso

 exports.createProduct = async (req, res) => { try { const newProduct = await Product.create(req.body) res.json(newProduct) } catch(err) { console.log(err) } }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Intente cambiar su función React onClick:

 for (let i = 0; i < values.length; i++) { const { price, quantity, weight } = values[i]; const res = await createProduct({ productName, price, quantity, weight }) console.log(res) }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!