S
S
Stanislav2017-01-23 22:00:05
MongoDB
Stanislav, 2017-01-23 22:00:05

How to check document uniqueness by two fields in mongoose schema?

Hi all.
I don't understand how to implement the idea.
There is a schema like this:

const schema = new Schema({
    post_id:        { type: Number, required: true },
    idGroup:       { type: String },
    createdAt:    { type: Date, default: Date.now }
});

When saving the document, you need to check the uniqueness of the post_id associated with idGroup
. if such a post_id exists for idGroup, then there is no need to save the document.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ro37A, 2017-01-23
@ms-dred

Look towards composite unique indexes.
Accordingly, inserting a new document with similar values ​​will cause a Duplicate key error with code 11000.
You may also need to disable autoIndex when creating a new schema, if you have not disabled it globally.
mongoose docks
Composite indexes
Unique indexes

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question