mongoose模式中的唯一Array对象

时间:2016-08-19 00:31:53

标签: express mongoose

我有一个会话架构,允许用户进行私密消息传递,因此每两个用户可以进行ONE对话,对话中的收件人应该是唯一的

/** Users in this conversation**/
var usersSchema = new Schema({
    id: {
        type: Schema.Types.ObjectId,
        index: true,
        required: true,
        ref: 'User'
    },

    name: {
        type: String,
        required: true
    }
});

/** For each message we will have the below **/
var messagesSchema = new Schema({
    from: {
        type: Schema.Types.ObjectId,
        required: true
    },
    content: {
        type: String,
        required: true
    },
    read: {
        type: Boolean,
        default: false
    }
}, {
    timestamps: true
});


/** Now all together inside the thread schema **/
var conversationsSchema = new Schema({

    users: {
        type: [usersSchema],
        required: true,
        index: true,
        unique: true
    },
    messages: [messagesSchema],


}, {
    timestamps: true
});

var Conversation = mongoose.model('Conversation', conversationsSchema);
module.exports.Conversation = Conversation;

我能想到的唯一方法是通过查看会话模式中users数组内的ID来手动检查。但是,我认为猫鼬有一种方法可以做到这一点。

1 个答案:

答案 0 :(得分:0)

您可以在userSchema中添加unique : true,仅允许对话中的唯一身份用户。

/** Users in this conversation**/
var usersSchema = new Schema({
    id: {
        type: Schema.Types.ObjectId,
        index: true,
        required: true,
        unique : true, //add unique behaviour here
        ref: 'User'
    },

    name: {
        type: String,
        required: true
    }
});