2017-07-18 25 views
0

我想阻止數據庫存儲空字段。當我更新我的收藏時,輸入已經空白的字段插入""。我不希望發生這種情況。如果該字段中包含數據,我只希望集合保存該字段。在mongoDB插入前清理數據

步驟1: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); 
} 

步驟2: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: ""存儲在集合中,因爲該字段爲空。我希望它被省略。

第3步: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,因爲沒有數據要保存在首位。

你是如何做到這一點的?

+0

不清楚你的意思。您正在使用'$ push',這裏「附加到數組」。你是否期待「奇異數據」呢?因此它不應該是一個數組。作爲一個例子,顯示文檔的初始狀態,然後顯示已更改的狀態。作爲一個解釋比你現在的代碼更清楚,它可能「完全做錯了」。 –

+0

在這種情況下可能會有多家公司。正如我所提到的,當我使用'$ push'運行函數來更新集合時,空白字段將使用'「」'保存到數據庫中。我已經更新了示例,以包含表單包含空白輸入字段時的集合。 – bp123

+0

您無法同時「更新」和「添加到」陣列。你** CAN **更新這個「單個」數組項目,並將其替換爲一些實際數據。就像我說的,你的問題很不明確,因爲你試圖用你不完全理解的操作來解釋它。最好通過示例來展示。另外解釋爲什麼這需要首先是一個數組。因爲我沒有看到爲什麼數據甚至應該包含在數組中的任何明確的理由。 –

回答

1

如果您將aldeed:meteor-collection2-coresimpl-schema結合使用,它會自動爲您刪除空字符串。 Collection2非常有用,它很好地增強了簡單模式。

autoValue(){ 
    if (this.isSet && !this.value.length) this.unset(); 
} 

這基本上說,「如果修改試圖將該字段設置爲一個零長度值然後將其刪除:

否則,您可以按如下添加autoValue到架構這些字符串字段修改器「。

+0

嗨@MichelFloyd,謝謝你。我正在使用collection2和簡單模式。我認爲我的問題可能與bug有關。既然你看起來有點古怪,你能否看看下面的鏈接並確認它是否是一個錯誤。 – bp123

+0

https://stackoverflow.com/questions/45180249/array-of-objects-passes-validation-but-doesnt-update-collection?noredirect=1#comment77355469_45180249 – bp123