【问题标题】:How to add multiple values to an object ID later in mongodb如何稍后在 mongodb 中将多个值添加到对象 ID
【发布时间】:2022-08-22 00:35:53
【问题描述】:

我正在尝试在对象 ID 中添加值。对象 ID 是之前创建的,但我想将来在对象 ID 中添加更多值。

这是我的 MongoDB 数据库:

[{
        label: \'colors\',
        options: [
            { label: \'Black\', value: 1 },
            { label: \'Green\', value: 2 },
        ]
    }]

我的期望当我发送一个新对象时,它会在 options 属性中插入一个新对象。假设我的新对象是 {label: \'blue\', value: 3} 它会是这样的:

[{
        label: \'colors\',
        object: [
            { label: \'Black\', value: 1 },
            { label: \'Green\', value: 2 },
            {label: \'blue\', value: 3} 
        ]
    },

我正在尝试这种方式,我正在存储以前的数据值,插入一个新值,并将其发送到后端。但它不工作。有什么不同的方法可以解决吗?

  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,我用的是put方法,不知道以后有没有其他插入新值的方法。

 // 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);
        })
  • 因为,options大批type 字段,您可以使用$push 向其中添加新对象。
  • 正如@prasad_ 已经说过的,您可以使用$push 而不是$set。如果您在filter 变量中引用ObjectId,您也有错字

标签: javascript arrays reactjs json mongodb


【解决方案1】:

你需要使用$推在数组中添加新对象。$set将使用新值重置您以前的值。也不要使用ObjectId,只需传递简单ID这需要是字符串。如果你想传入 ObjectId 然后使用猫鼬.Types.Objectid(id).

【讨论】:

    猜你喜欢
    • 2011-10-28
    • 2022-07-13
    • 1970-01-01
    • 2023-03-22
    • 2020-04-22
    • 2021-11-06
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多