看看添加自定義的驗證與aldeed:簡單模式,連接到您的收藏與aldeed:collections2
customUsers = new Mongo.Collection('customUsers');
customUsers.attachSchema(new SimpleSchema({
name: {
type: new SimpleSchema({
first: { type: String},
last: { type: String},
}),
},
emails: {
type: Array,
custom: function() {
if (_.compact(_.pluck(this.value, 'primary')).length !== 1) {
return 'NotOnePrimaryEmail';
}
},
},
'emails.$': {
type: Object,
},
'emails.$.address': {
type: String,
regEx: SimpleSchema.RegEx.Email,
},
'emails.$.verified': {
type: Boolean,
},
'emails.$.primary': {
type: Boolean,
},
}));
SimpleSchema.messages({
NotOnePrimaryEmail: 'You must have one, and only one, email marked as primary',
});
if (Meteor.isServer) {
Meteor.startup(function() {
objValid = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: '[email protected]',
verified: true,
primary: true,
}, {
address: '[email protected]',
verified: true,
primary: false,
},],
};
objNoPrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: '[email protected]',
verified: true,
primary: false,
}, {
address: '[email protected]',
verified: true,
primary: false,
},],
};
objMultiplePrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: '[email protected]',
verified: true,
primary: true,
}, {
address: '[email protected]',
verified: true,
primary: true,
},],
};
[objValid, objNoPrimary, objMultiplePrimary].forEach(
function(obj) {
try {
customUsers.insert(obj);
console.log('Object was valid, inserted into collection');
} catch (err) {
console.log('Error: ' + err.sanitizedError.reason);
}
}
);
});
}
從服務器控制檯輸出:
~/test/schema$ meteor
[[[[[ ~/test/schema ]]]]]
=> Started proxy.
=> Started MongoDB.
=> Started your app.
=> App running at: http://localhost:3000/
I20151008-15:04:15.280(13)? Object was valid, inserted into collection
I20151008-15:04:15.281(13)? Error: You must have one, and only one, email marked as primary
I20151008-15:04:15.281(13)? Error: You must have one, and only one, email marked as primary
我不相信的MongoDB將強制執行這個給你。您可以將「primary:true」鍵值對添加到主電子郵件地址,並從其他地方省略。你必須通過代碼來強制執行。 –