字段唯一的猫鼬模式"/>
2个字段唯一的猫鼬模式
我正在尝试将2个字段设置为彼此唯一,并且没有重复项。
代码是这里:
const Connection = mongoose.model("Connection", new mongoose.Schema({
from_friend: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Friend'
},
to_friend: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Friend'
}
}))
exports.Connection = Connection;
回答如下:您可以使用包含两个字段的唯一索引来执行此操作
const ConnectionSchema = mongoose.Schema({
from_friend: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Friend'
},
to_friend: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Friend'
}
});
ConnectionSchema.index({ from_friend: 1, to_friend: 1 }, { unique: true });
module.exports = mongoose.model('Connection', ConnectionSchema);
更多推荐
2个字段唯一的猫鼬模式
发布评论