【问题标题】:Apply unique only inside array or sub-document mongoose仅在数组或子文档猫鼬内应用唯一
【发布时间】:2021-05-10 08:45:00
【问题描述】:

希望你做得很好。

我有这样的架构:

const Person = new mongoose.Schema({
  username: {
    type: String,
    required: [true, "Name is a required field"],
    unique: [true, "Another Person with the same name already exists"],
    trim: true
  },
  friends: [
    {
      name: {
        type: String,
        required: [true, "Every friend must have a name"],
        unique: [true, "Another friend with the same name already exists"],
        trim: true
      },
     favoriteFood: String
    }
  ],
  createdAt: {
    type: Date,
    default: Date.now()
  }
});

这里我希望名字在朋友数组中是唯一的,显然不同的人可以有相同的朋友。但是 MongoDB 不允许我用这个实现在不同的人对象中定义两个同名的人。我该怎么做?如何强制朋友的名字只对一个人是唯一的?

我发现的另一件事是,如果我尝试在一个人下添加两个同名的朋友,它将被接受,但如果您尝试在两个不同的人之间添加相同的朋友名,则会引发重复错误。它与应有的完全相反,或者至少与我想要的相反。

谢谢。

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:

    似乎没有默认方式,或者某种索引可以做到这一点,所以我们必须手动检查重复。我是这样做的:

    //check for duplications
    Person.pre("save", function (next) {
      const friends = this.friends;
      const lookup = friends.reduce((a, e) => {
        a[e.name] = ++a[e.name] || 0;
        return a;
      });
      const duplicates = friends.filter(friend => lookup[friend.name]);
      if (duplicates.length) next(new Error("There are two friends with the same name"));
      else next();
    });
    

    【讨论】:

      猜你喜欢
      • 2014-11-12
      • 1970-01-01
      • 2019-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-24
      • 2022-11-10
      相关资源
      最近更新 更多