如何使用JSON Schema Faker生成从0开始的自增ID?
Absolutely! You can definitely achieve auto-incrementing IDs starting at 0 with JSON Schema Faker—the default autoIncrement behavior starts at a random value, but a simple custom generator will let you take full control of the starting number.
Here's how to do it:
1. Use a closure-based counter for full control
The key is to maintain your own counter variable outside the schema, then use a custom generator function to increment it each time a new ID is generated. This ensures you start exactly at 0 and increment sequentially.
Example code:
const jsf = require('json-schema-faker'); // Initialize our counter starting at 0 let idCounter = 0; // Define your schema with a custom ID generator const userSchema = { type: 'object', properties: { id: { type: 'integer', // Custom generator: return current counter value, then increment 'x-jsf': () => idCounter++ }, username: { type: 'string', faker: 'internet.userName' }, email: { type: 'string', faker: 'internet.email' } }, required: ['id', 'username', 'email'] }; // Generate 5 sample users to test for (let i = 0; i < 5; i++) { const user = jsf.generate(userSchema); console.log(user); }
This will output users with IDs 0, 1, 2, 3, 4—exactly what you're looking for.
2. Resetting the counter
If you need to restart the sequence from 0 later (e.g., for a new batch of data), just reset the counter variable:
idCounter = 0; // Now the next generated ID will be 0 again
Why the default autoIncrement uses a random start
The built-in autoIncrement feature starts at a random value by design—it's meant to avoid ID collisions if you're using multiple instances of JSON Schema Faker or generating data across different sessions. But for controlled, sequential IDs starting at 0, the custom counter method is the way to go.
内容的提问来源于stack exchange,提问作者Mateusz Cholewka

