The problem is, I don't know if there's something wrong with the way I'm inserting the data in the post, or if the problem is with the HTML syntax of the object properties I'm trying to access the array.
This is my model and I want to insert a value in "cantidad" of the "MaterialesProductos" array.
const mongoose = require('mongoose') const Schema = mongoose.Schema; const bodyParser = require('body-parser') const ProductoSchema = new Schema({ IdProducto:{type:String}, MaterialesProductos:[{nombre:{type:String},cantidad:{type:Number}}], precio:{type:Number}, image:{type:String}, nombre:{type:String}, description:{type:String}, }); const Producto = mongoose.model('Producto',ProductoSchema); module.exports = Producto;
This is my post, I use "req.body" to insert all the data. Always clear the array.
const Producto = require('../models/Productos.js') const fileUpload = require('express-fileupload') const path = require('path') module.exports = (req,res)=>{ console.log(req.body) let image = req.files.image; image.mv(path.resolve(__dirname,'..','public/img',image.name),async (error)=>{ await Producto.create({ ...req.body, image: '/img/' image.name }) res.redirect('/AgregarProductos') }) }
I've tried using MaterialesProductos[].cantidad or MaterialesProductos[][cantidad] etc. but I can't insert the value.
<div class="control-group"> <div class="form-group floating-label-form-group controls"> <input type="button" name="abrirse" id="open" value="Agregar materiales"> <div id="popup" style="display: none;"> <div class="content-pop"> <div><a href="#" id="close">X</a></div> <% for (var a = 0; a < materiales.length; a ) { %> <div> <%=materiales[a].Description%> <input type="number" value="0" name="MaterialesProductos.cantidad" min="0"> </div> <% } %> </div> </div> </div> </div>
Well, I did some research and didn't find a solution. So I have to do it manually.
Using
MaterialesProductos[nombre]
(can be anything), I usereq.body.MaterialesProductos[nombre]
to get the value in the array and I can access it. Using$push
(I can't insert or create it, so I can onlyupdateOne
) I first create the document and then after updating it add an array containing the two objects.Things like this: