Master Mind
Introduction
MasterMind
is helper class that is fully dedicated to manage the model id
field, it is used internally by the model class to keep tracking of generated ids and gets the proper next id.
For SQL People, consider it more likely the INFORMATION_SCHEMA
table.
Master Mind Collection
Any model that is being saved, the model's collection name and the last saved id are stored in MasterMind
collection, the purpose of this collection is to keep tracking of the last saved id for each collection
Get last id
If you want to get the last id of any collection, consider the following snippet:
import { masterMind } from "@mongez/monpulse";
async function main() {
const lastId = await masterMind.getLastId("categories");
console.log(lastId); // 512344
}
main();
We imported masterMind
as an object, if you want to create a new instance of it, you may import MasterMind
class instead.
Generate next id
To generate the next id of any collection, consider the following snippet:
import { masterMind } from "@mongez/monpulse";
async function main() {
const initialId = 1;
const incrementBy = 1;
const nextId = await masterMind.getNextId(
"categories",
initialId,
incrementBy
);
console.log(nextId); // 1
const nextId2 = await masterMind.getNextId(
"categories",
initialId,
incrementBy
);
console.log(nextId); // 2
}
main();
getNextId
method accepts three arguments:
collectionName
: The collection nameinitialId
: The initial id value, it will be used if the collection name does not exist in theMasterMind
collectionincrementBy
: The increment value, it will be used if the collection name does not exist in theMasterMind
collection