I
I
ikerya2020-05-11 19:59:25
MongoDB
ikerya, 2020-05-11 19:59:25

Is it ok to use Set in .pre('save') mongoose to guarantee uniqueness of indexes?

Is it ok to use Set in .pre('save') mongoose to ensure indexes are unique?

const schema = new mongoose.Schema({
    id: {
        type: Number,
        unique: true
    },
    name: String
});

const store = new Set(); 
const getPathIndexName = (path, value) => `${path}_${value}`;
const paths = Object.keys(schema.paths)
  .map((key) => {
      const {
          path,
          _index
      } = schema.paths[key];

      if (!_index || !_index.unique) {
          return null;
      }

      return path;
  })
  .filter((path) => !!path);

// paths = [ 'id' ]

function checkUniqueness(next) {
    const self = this;

    // self = {id: 5, name: 'test'}
  
    const indexes = paths
        .map((path) => {
            return self[path] ?
                getPathIndexName(path, self[path]) : // getPathIndexName('id', 5) = 'id_5'
                null;
        })
        .filter((index) => !!index);

  // indexes = [ 'id_5' ]

    for (let i = 0; i < indexes.length; i++) {
        const index = indexes[i];

        if (store.has(index)) {
            throw new Error(`Duplicate: ${index}`);
        }

        store.add(index);
    }

    next();
};

schema.pre('save', checkUniqueness);

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question