Skip to content

Commit

Permalink
Merge pull request #164 from AquilaCMS/randomizedID
Browse files Browse the repository at this point in the history
Self generated _id for all collections
  • Loading branch information
devaquila committed May 4, 2022
2 parents c6a3707 + eb64467 commit 78ae4fe
Show file tree
Hide file tree
Showing 3 changed files with 983 additions and 527 deletions.
23 changes: 23 additions & 0 deletions orm/plugins/generateID.js
@@ -0,0 +1,23 @@
const mongoose = require('mongoose');
const utilsDatabase = require('../../utils/database');

const generate = () => mongoose.Types.ObjectId(`ff${[...Array(22)].map(() => Math.floor(Math.random() * 16).toString(16)).join('')}`);

module.exports = function generateID(schema) {
schema.pre('save', async function (next) {
if (this._id.id[0] !== 255 && this.isNew) this._id = generate();
await utilsDatabase.preUpdates(this, next, schema);
});

schema.pre('insertMany', async function (next, docs) {
docs.forEach((insert) => {
if (!insert._id || insert._id[0] !== 'f') insert._id = generate();
});
await utilsDatabase.preUpdates(this, next, schema);
});

schema.pre('findOneAndUpdate', async function (next) {
if (this.options.upsert && this._conditions._id && this._conditions._id.id[0] !== 255 ) this._id = generate();
await utilsDatabase.preUpdates(this, next, schema);
});
};
2 changes: 1 addition & 1 deletion utils/database.js
Expand Up @@ -43,7 +43,7 @@ const connect = async () => {
await checkConnect();
mongoose.set('objectIdGetter', false);
}

mongoose.plugin(require('../orm/plugins/generateID'));
return mongoose;
};

Expand Down

0 comments on commit 78ae4fe

Please sign in to comment.