如何将值插入数组的对象属性?
P粉718730956
P粉718730956 2024-02-26 17:17:47
0
1
305

问题是,我不知道在帖子中插入数据的方式是否有问题,或者问题是否出在我尝试访问数组的对象属性的 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>

P粉718730956
P粉718730956

全部回复(1)
P粉563831052

嗯,我研究了一下,没有找到解决方案。所以我必须手动完成。

使用 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

并且工作了。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!