在mongoDB插入

时间:2017-07-18 04:59:24

标签: mongodb reactjs meteor

我想阻止数据库存储空字段。当我更新我的集合时,输入空白的字段插入""。我不希望这种情况发生。如果字段中包含数据,我只希望集合保存字段。

第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,因为首先没有要保存的数据。

你是怎么做到的?

1 个答案:

答案 0 :(得分:1)

如果您将aldeed:meteor-collection2-coresimpl-schema结合使用,它会自动删除空字符串。 Collection2非常有用,它很好地增加了简化模式。

否则,您可以为这些字符串字段的架构添加autoValue,如下所示:

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

其中基本上说“如果修饰符试图将此字段设置为零长度值,则将其从修饰符中删除。”

相关问题