Javascript 确保数组中只有一个元素具有给定属性
我想在包含数组的集合上设置布尔标志。作为数据示例:Javascript 确保数组中只有一个元素具有给定属性,javascript,mongodb,meteor,Javascript,Mongodb,Meteor,我想在包含数组的集合上设置布尔标志。作为数据示例: { _id: "12341234", name: { first: 'Jeff', last: 'Jefferson' }, emails: [{ address: 'fake@fake.org', verified: true, primary: true }, { address: 'fake@fake.net', verified: true, prima
{
_id: "12341234",
name: {
first: 'Jeff',
last: 'Jefferson'
},
emails: [{
address: 'fake@fake.org',
verified: true,
primary: true
}, {
address: 'fake@fake.net',
verified: true,
primary: false
}]
}
在这个表中的每个条目上,我希望电子邮件数组中只有一个条目是primary:true
使用表中的键,可以执行如下操作以确保唯一性:
Meteor._ensureIndex({ 'name.last': 1 }, { unique: 1 });
是否有一种方法可以在单个条目中的数组上执行此操作?请查看使用aldeed:simple schema添加自定义验证,并使用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: 'fake@fake.org',
verified: true,
primary: true,
}, {
address: 'fake@fake.net',
verified: true,
primary: false,
},],
};
objNoPrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake@fake.org',
verified: true,
primary: false,
}, {
address: 'fake@fake.net',
verified: true,
primary: false,
},],
};
objMultiplePrimary = {
name: {
first: 'Jeff',
last: 'Jefferson',
},
emails: [{
address: 'fake@fake.org',
verified: true,
primary: true,
}, {
address: 'fake@fake.net',
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
键值对添加到主电子邮件地址,并从其余地址中省略即可。您必须通过代码强制执行此操作。