2个字段唯一的猫鼬模式

编程入门 行业动态 更新时间:2024-10-05 23:21:11

2个<a href=https://www.elefans.com/category/jswz/34/1771443.html style=字段唯一的猫鼬模式"/>

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个字段唯一的猫鼬模式

本文发布于:2024-05-07 04:59:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754357.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   模式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!