简体   繁体   English

仅在数组或子文档 mongoose 内应用唯一

[英]Apply unique only inside array or sub-document mongoose

Hope you are doing good.希望你做得很好。

I have a schema like this:我有这样的架构:

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()
  }
});

here I want name just be unique inside friends array, obviously different persons can have the same friend.这里我希望名字在朋友数组中是唯一的,显然不同的人可以有相同的朋友。 but MongoDB does not let me define two person with the same name inside different persons object with this implementation.但是 MongoDB 不允许我用这个实现在不同的人 object 中定义两个同名的人。 how can I do that?how to force friends name only be unique for one person?我该怎么做?如何强制朋友的名字只对一个人是唯一的?

another thing I found is if I try to add two friends with the same name under one person it will be accepted, but if you try to add same friend name across two different persons, it will throw the error of duplication.我发现的另一件事是,如果我尝试在一个人下添加两个同名的朋友,它将被接受,但是如果您尝试在两个不同的人之间添加相同的朋友名,则会引发重复错误。 it is the exact opposite of what it should be, or at least opposite of what I want.它与它应该是完全相反的,或者至少与我想要的相反。

thanks.谢谢。

It seems there is no default way, or some sort of indexing that can do that, so we have to check for duplication manually.似乎没有默认方式,或者某种索引可以做到这一点,所以我们必须手动检查重复。 I done it this way:我是这样做的:

//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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM