问题是,我不知道在帖子中插入数据的方式是否有问题,或者问题是否出在我尝试访问数组的对象属性的 HTML 语法上.
这是我的模型,我想在“MaterialesProductos”数组的“cantidad”中插入一个值。
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},
descripcion:{type:String},
});
const Producto = mongoose.model('Producto',ProductoSchema);
module.exports = Producto;
这是我的帖子,我用“req.body”插入所有数据。始终将数组清空。
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')
})
}
我已经尝试过使用 MaterialesProductos[].cantidad 或 MaterialesProductos[][cantidad] 等,但我无法插入该值。
<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].Descripcion%>
<input type="number" value="0" name="MaterialesProductos.cantidad" min="0">
</div>
<% } %>
</div>
</div>
</div>
</div> Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
嗯,我研究了一下,没有找到解决方案。所以我必须手动完成。
使用
MaterialesProductos[nombre](可以是任何内容),我使用req.body.MaterialesProductos[nombre]获取数组中的值,我可以访问它。 使用$push(我无法插入或创建它,所以我只能updateOne)我首先创建文档,然后在更新它后添加包含两个对象的数组。类似这样的事情:
const Producto = require('../models/Productos.js') const fileUpload = require('express-fileupload') const path = require('path') module.exports = (req, res) => { 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 }) for (a=0; a并且工作了。