[英]Apply unique only inside array or sub-document mongoose
希望你做得很好。
我有這樣的架構:
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 不允許我用這個實現在不同的人 object 中定義兩個同名的人。 我該怎么做?如何強制朋友的名字只對一個人是唯一的?
我發現的另一件事是,如果我嘗試在一個人下添加兩個同名的朋友,它將被接受,但是如果您嘗試在兩個不同的人之間添加相同的朋友名,則會引發重復錯誤。 它與它應該是完全相反的,或者至少與我想要的相反。
謝謝。
似乎沒有默認方式,或者某種索引可以做到這一點,所以我們必須手動檢查重復。 我是這樣做的:
//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.