【发布时间】:2023-03-21 21:34:01
【问题描述】:
我想防止数据库存储空字段。当我更新我的收藏时,输入已留空的字段插入""。我不希望这种情况发生。如果字段中有数据,我只希望集合保存该字段。
第一步:Existing document state when the form first loads
constructor(props) {
super(props);
this.state = {
careerHistoryPositions: [
{
company: '',
uniqueId: uniqueId,
title: '',
}
]
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
}
第二步:Show new data to update
this.setState = {
careerHistoryPositions: [
{
uniqueId: "1",
company: "Company 1",
title: "Title 1",
}
{
uniqueId: "2",
company: "",
title: "Title 2",
}
]
};
在第 2 步中,第二个位置,公司为空白,但它在 setState 中显示为 ""。当我运行更新以将数据推送到集合中时,我不希望 company: "" 存储在集合中,因为该字段为空。我希望它被省略。
第三步:How I'm pushing it into the database
handleFormSubmit(event) {
ProfileCandidate.update({
_id: this.state.profileCandidateCollectionId
}, {
$unset: {
'careerHistoryPositions': {}
}
})
this.state.careerHistoryPositions.map((position) => {
ProfileCandidate.update({
_id: this.state.profileCandidateCollectionId
}, {
$push: {
'careerHistoryPositions': {
company: position.company,
uniqueId: position.uniqueId,
title: position.title,
}
}
});
}
}
结果:How the collection currently looks
{
"_id": "BoDb4Zztq7n3evTqG",
"careerHistoryPositions": [
{
"uniqueId": 1,
"company": "Company 1",
"title": "Title 1",
}
{
"uniqueId": 2,
"company": "",
"title": "Title 2",
}
]
}
期望的收集结果
{
"_id": "BoDb4Zztq7n3evTqG",
"careerHistoryPositions": [
{
"uniqueId": 1,
"company": "Company 1",
"title": "Title 1",
}
{
"uniqueId": 2,
"title": "Title 2",
}
]
}
在我的desired collection outcome 中,第二个对象不包含company,因为首先没有要保存的数据。
你是怎么做到的?
【问题讨论】:
-
不清楚你的意思。您在此处使用“附加到数组”的
$push。您是否期待“奇异数据”?因此它不应该是一个数组。显示文档的初始状态,然后显示更改后的状态作为示例。这将比您当前的代码更清楚地解释,这“可能”完全做错了。 -
这种情况下可能有多家公司。正如我在运行函数以使用
$push更新集合时提到的那样,空白字段将使用""保存到数据库中。我更新了示例以包含当表单包含空白输入字段时集合的外观。 -
您不能同时“更新”和“添加到”一个数组。您可以更新这个“单个”数组项并将其替换为一些实际数据。就像我说的那样,您的问题非常不清楚,因为您试图通过使用您不完全理解的操作来解释它。最好通过示例来展示。还要解释为什么这首先需要是一个数组。因为我看不出为什么数据甚至应该包含在数组中。
-
嗨@NeilLunn,很抱歉造成混乱。老实说,我不确定如何解释这一点。这需要是一个数组,因为用户可以有多个 careerHistoryPositions。查看更新。
-
老实说,这仍然是“一清二楚”,并且仍然是您告诉我们您的代码“做什么/您希望它做什么”而不是“简单地描述过程”的主要原因。那么实际上需要发生什么?您是否正在尝试将“公司”字段为空的内容与其他数据“交换”?您是否正在尝试“添加新数据”?您是否正在尝试“替换所有数据”?因为您的问题的阅读方式是开始说一件事然后与另一件事相矛盾。 改为。 1. 从您现有的文档状态开始。 2. 显示要更新的新数据。 3.显示新的更新状态。不能错过。