2016-08-19 3 views
0

ich ein Gespräch Schema habe die Benutzer für privates Messaging ermöglicht es, jeweils zwei Benutzer daher in ONE Gespräch sein, der Empfänger in den Gesprächen solltenEinzigartige Array-Objekte in Mungo Schema

/** 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; 

Der einzige Weg, eindeutig sein Ich kann mir vorstellen, dass ich das manuell überprüfe, indem ich mir die IDs im Benutzer-Array im Konversationsschema anschaue. Ich denke jedoch, dass es einen Weg gibt, dies zu tun.

Antwort

0

Sie können in Ihrem userSchema unique : true hinzufügen, um nur eindeutigen Benutzern in einer Konversation zu erlauben.

/** 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 
    } 
}); 
+0

Ich möchte einzigartige zwei Benutzer in allen Gesprächen. – Othman