const UserSchema = new Schema(
{
userId: String,
userName: String,
password: String,
friendList: [
{type: Schema.Types.ObjectId, ref: 'User'}
],
},
{
timestamps: true
}
)
请问如何能保证friendList数组内的用户是唯一的呢
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
在Mongoose中,要保证数组内的对象(这里是指friendList
中的用户)是唯一的,你可以通过自定义验证器实现这一需求。Mongoose允许你在Schema级别定义验证逻辑来确保数据的唯一性、完整性等。
下面是如何在你的UserSchema中添加一个自定义验证器以确保friendList
中的用户ID不重复:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema(
{
userId: String,
userName: String,
password: String,
friendList: [
{type: Schema.Types.ObjectId, ref: 'User'}
],
},
{
timestamps: true
}
);
// 自定义验证器函数
UserSchema.path('friendList').validate(async (value) => {
// 如果friendList为空,则直接通过验证
if (!value || value.length === 0) return true;
// 将friendList转换为Set以去除重复并比较长度,如果长度不同说明有重复
const uniqueIds = new Set(value);
if (uniqueIds.size !== value.length) {
return false; // 有重复,验证失败
}
// 可选:进一步检查数据库中这些ID是否已存在且不重复(这一步可能需要优化,特别是当friendList很大时)
// 注意:这一步骤可能会导致性能问题,特别是对于大规模数据集,因为它涉及数据库查询。
// 以下代码是一个简化的示例,并未考虑最佳实践或错误处理。
try {
const friends = await User.find({_id: {$in: value}});
return friends.length === uniqueIds.size;
} catch (error) {
console.error('Error checking for duplicate friends:', error);
return false; // 遇到错误时也视为验证失败
}
}, 'Friend list contains duplicate user IDs.');
module.exports = mongoose.model('User', UserSchema);
请注意,上述代码中的数据库查询部分(可选步骤)是为了演示如何进一步确保数据库层面的唯一性。在实际应用中,这种做法可能并不高效,尤其是当friendList
非常长时,因为它会导致多次数据库查询。更高效的做法可能是在添加朋友时就进行检查,或者使用数据库级别的索引和约束(如果数据库支持且符合你的业务场景)。然而,Mongoose本身并不直接支持在子文档数组上设置唯一性约束,因此自定义验证器是比较灵活的解决方案。