开发者社区 问答 正文

mongoose如何保证填充的数据是唯一的

const UserSchema = new Schema(
  {
    userId: String,
    userName: String,
    password: String,
    friendList: [
      {type: Schema.Types.ObjectId, ref: 'User'}
    ],
  },
  {
    timestamps: true
  }
)

请问如何能保证friendList数组内的用户是唯一的呢

展开
收起
xiawang1024 2021-10-14 17:09:20 11920 分享 版权
阿里云 AI 助理回答

在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本身并不直接支持在子文档数组上设置唯一性约束,因此自定义验证器是比较灵活的解决方案。

有帮助
无帮助
AI 助理回答生成答案可能存在不准确,仅供参考
0 条回答
写回答
取消 提交回答
问答地址: