I have a conversation schema which will allow users for private messaging, each two users can be in ONE
conversation therefore, the recipients in the conversations should be unique
我有一个会话模式,允许用户进行私人消息传递,因此每两个用户可以在一个对话中,对话中的接收者应该是唯一的
/** 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;
The only way I can think of is to manually check by looking into the IDs inside the users array in the conversation schema. However, I think there is a way in mongoose to do that.
我能想到的唯一方法是通过查看会话模式中users数组内的ID来手动检查。但是,我认为猫鼬有一种方法可以做到这一点。
1 个解决方案
#1
0
You can add unique : true
in your userSchema to only allow unique users in a conversation.
您可以在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
}
});
#1
0
You can add unique : true
in your userSchema to only allow unique users in a conversation.
您可以在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
}
});