【发布时间】: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