2017-07-07 112 views
0

我想插入一個數組到對象中,我沒有任何運氣。我認爲架構基於驗證拒絕它,但我不知道爲什麼。如果我console.log(this.state.typeOfWork)和檢查typeof它指出了一個Object包含:簡單模式驗證錯誤

(2) ["Audit - internal", "Audit - external"] 
0: "Audit - internal" 
1: "Audit - external" 

更新後我的集合包含:

"roleAndSkills": { 
    "typeOfWork": [] 
    } 

例子:Schema

roleAndSkills: { type: Object, optional: true }, 
    'roleAndSkills.typeOfWork': { type: Array, optional: true }, 
    'roleAndSkills.typeOfWork.$': { type: String, optional: true } 

例子:update

ProfileCandidate.update(this.state.profileCandidateCollectionId, { 
     $set: { 
     roleAndSkills: { 
      typeOfWork: [this.state.typeOfWork] 
     } 
     } 
    }); 
+0

你能展示你的整個更新調用和集合模式嗎? – mparkitny

回答

0

typeOfWorkArray。你應該在它把你的價值:

$push: { 
    "roleAndSkills.typeOfWork": this.state.typeOfWork 
} 

多個值:

$push: { 
    "roleAndSkills.typeOfWork": { $each: [ "val1", "val2" ] } 
} 

mongo $push operator

mongo dot notation

+0

我得到這個錯誤:'未捕獲的錯誤:篩選出不在模式中的鍵後,您的修飾符現在爲空' – bp123

+0

雙引號不會返回錯誤,但是它也不會添加到數組中。沒有錯誤。 – bp123

+0

您是否嘗試推送一個或多個值? –

0

簡單的模式有一些問題與對象或數組的驗證,我有我最近開發的一個應用程序也出現同樣的問題

你能做什麼? 好,我做什麼,在Collections.js文件,當你說:

typeOfWork:{ 
    type: Array 
} 

嘗試添加屬性黑盒:真正的,就像這樣:

typeOfWork:{ 
    blackbox: true, 
    type: Array 
} 

這會告訴你的模式,它此字段正在使用數組,但忽略進一步驗證。

我做的驗證是在main.js上,只是爲了確保我沒有空數組而且數據是純文本。

按照這裏要求的是我的更新方法,即時我的情況我使用的對象不是數組,但它的工作方式相同。

editUser: function (editedUserVars, uid) { 
     console.log(uid); 
     return Utilizadores.update(
     {_id: uid}, 
     {$set:{ 
      username: editedUserVars.username, 
      usernim: editedUserVars.usernim, 
      userrank: {short: editedUserVars.userrank.short, 
      long: editedUserVars.userrank.long}, 
      userspec: {short: editedUserVars.userspec.short, 
      long: editedUserVars.userspec.long}, 
      usertype: editedUserVars.usertype}}, 
     {upsert: true}) 

    }, 

這裏收集模式

UtilizadoresSchema = new SimpleSchema({ 
username:{ 
    type: String 
}, 
usernim:{ 
    type: String 
}, 
userrank:{ 
    blackbox: true, 
    type: Object 
}, 
userspec:{ 
    blackbox: true, 
    type: Object 
}, 
usertype:{ 
    type: String 
} 
}); 
Utilizadores.attachSchema(UtilizadoresSchema); 

希望它可以幫助

羅布

+0

嘗試這個,但沒有更多的運氣。你是如何編寫更新方法的? – bp123

+0

你沒有檢查我的編輯@ bp123 – RSamurai

+0

沒有。 Simpleschema讓我瘋狂。 – bp123

0

幽州this.state.typeOfWork陣列(串),但是當你.update()你您將文件括在方括號內:

ProfileCandidate.update(this.state.profileCandidateCollectionId, { 
    $set: { 
    roleAndSkills: { 
     typeOfWork: [this.state.typeOfWork] 
    } 
    } 
}); 

只需去除多餘的方括號:

ProfileCandidate.update(this.state.profileCandidateCollectionId, { 
    $set: { 
    roleAndSkills: { 
     typeOfWork: this.state.typeOfWork 
    } 
    } 
}); 

此外,由於你的數組只是一個字符串數組,你可以通過[String]宣佈它是這樣的類型的簡化模式的位:

'roleAndSkills.typeOfWork': { type: [String] } 

請注意,對象和數組默認是可選的,因此您甚至可以省略可選標誌。

+0

我很久以前就試過了。出於某種原因,它不起作用。陣列真的讓我感到困惑。 – bp123