Alex Wohlbruck
Alex Wohlbruck

Reputation: 1436

Mongoose - don't allow documents to have identical arrays

I want to create a database schema where a document cannot have an array that is identical to that of another document. So, say I have the schema conversations:

var ConversationSchema = new Schema({
    name: String,
    participants: {
        type: [{
            type: Schema.Types.ObjectId,
            ref: 'User'
        }]
    }
});

Now if I create two conversations with the same participants, how can I validate this so that the second one will fail, but the third will not?

var conversation1 = new Conversation({
    name: "Hello",
    participants: ['12345', '09876']
});

var conversation2 = new Conversation({
    name: "World",
    participants: ['12345', '09876']
});

var conversation3 = new Conversation({
    name: "Group chat",
    participants: ['12345', '09876', '13579']
});

conversation1.save(); // Valid
conversation2.save(); // Invalid - conversation already exists
conversation3.save(); // Valid

Upvotes: 0

Views: 47

Answers (1)

TGrif
TGrif

Reputation: 5941

I guess you could use some custom Mongoose validation before saving your data. But this is not really a schema thing, as Kevin said in his comment, since you will need to make a database query to compare already existing array with the new one.
Something like this (not tested):

function checkArray(arr) {
// here make a call to the db to compare existing array with arr
}

var ConversationSchema = new Schema({
    name: String,
    participants: {
        type: [{
            type: Schema.Types.ObjectId,
            ref: 'User',
            validate: checkArray
        }]
    }
});

No better idea for now.

Upvotes: 1

Related Questions