【发布时间】: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