
Product
Introducing GitHub Actions Scanning Support
Detect malware, unsafe data flows, and license issues in GitHub Actions with Socket’s new workflow scanning support.
mongoose-test-factory
Advanced tools
A comprehensive Mongoose plugin for generating realistic test data with schema analysis, factory patterns, and relationship management
Mongoose Test Factory is a powerful and intuitive data generation tool for Mongoose. It completely eliminates the hassle of manually creating mock data for your tests, database seeding, or application prototypes.
By intelligently analyzing your Mongoose schemas, it generates realistic, valid, and context-aware data with an elegant, fluent API. Stop writing tedious mock objects and start building meaningful test data in seconds.
Testing and development should be fast and efficient. Manually creating test data is slow, error-prone, and doesn't scale. This factory is built on a simple philosophy: your schema definition is the ultimate source of truth, and it should be all you need to generate perfect test data.
mongoose-test-factory
bridges the gap between your schema and your testing needs, letting you focus on writing great code instead of mocking data.
required
, min
, max
, enum
, etc.), and default values.email
, name
, password
, or productPrice
to generate contextually relevant data using @faker-js/faker
.build()
: Creates lightweight, plain JavaScript objects.make()
: Creates unsaved Mongoose document instances.create()
: Creates and saves Mongoose documents directly to your database.The factory follows a sophisticated, multi-step process to generate the highest quality data for your models:
.factory()
method into your model, making it accessible everywhere.YourModel.factory()
, the plugin performs a deep analysis of your schema. It maps out all fields, their data types, validation rules (like required
, min
, max
, enum
), and default values.userEmail
, lastName
, avatarUrl
). It uses a powerful pattern-recognition engine to understand the semantic meaning of the field, going far beyond just its data type.faker.internet.email()
for an email
field). If not, it falls back to a generator appropriate for the field's data type, always respecting the validation rules..with()
method is applied at the end of the process, giving you the final say on the generated object's shape.object
(build
), a Mongoose instance (make
), or a database-saved document (create
).Install the package and its peer dependencies using your favorite package manager.
pnpm add --save-dev mongoose-test-factory @faker-js/faker mongoose
npm install --save-dev mongoose-test-factory @faker-js/faker mongoose
yarn add --dev mongoose-test-factory @faker-js/faker mongoose
Note:
mongoose
and@faker-js/faker
are required peer dependencies and must be installed in your project.
Let's see how easy it is to get up and running.
import mongoose, { Schema, Model } from 'mongoose';
import mongooseTestFactory from 'mongoose-test-factory';
// 1. Define your Mongoose interface and schema
interface User extends mongoose.Document {
name: string;
email: string;
age: number;
isActive: boolean;
}
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
age: { type: Number, min: 18 },
isActive: { type: Boolean, default: true },
});
// 2. Apply the plugin to your schema
userSchema.plugin(mongooseTestFactory);
// 3. Create your Mongoose model
const User = mongoose.model<User>('User', userSchema);
// 4. That's it! You're ready to generate data.
async function run() {
// Generate a single plain object with realistic, valid data
const userObject = User.factory().build();
console.log('Built Object:', userObject);
// -> { name: 'Eleanore Glover', email: 'glover.eleanore@example.com', age: 42, isActive: true }
// Generate and save 5 users directly to the database
const savedUsers = await User.factory(5).create();
console.log('Saved Users:', savedUsers.length); // -> 5
// Generate a specific user by overriding generated values
const adminUser = await User.factory()
.with({ name: 'Admin User', age: 99 })
.create();
console.log('Admin User:', adminUser.name, adminUser.age); // -> 'Admin User' 99
}
FactoryPlugin
)For a consistent testing environment, you can set global configurations once in your test setup file (e.g., jest.setup.ts
).
import { FactoryPlugin } from 'mongoose-test-factory';
FactoryPlugin.configure({
/**
* By setting a seed, you ensure that @faker-js/faker generates the same
* sequence of data every time your tests run. This makes tests
* deterministic and prevents random failures.
*/
seed: 1337,
/**
* Set a default locale for internationalized data (e.g., names, addresses).
* Supports any locale supported by Faker.js.
*/
locale: 'en_US',
/**
* Set to true to see detailed logs from the factory during its
* analysis and generation process. Useful for debugging.
*/
debug: false,
factory: {
/**
* When using .create() for multiple documents, they are inserted in batches.
* This sets the default size for those batches.
*/
defaultBatchSize: 100,
}
});
build
, make
, and create
The factory offers three distinct ways to generate data, each with a specific use case.
build()
-> Plain JavaScript Object{ name: '...', email: '...' }
// Build a single user object
const user = User.factory().build();
// Build an array of 3 user objects
const users = User.factory(3).build();
make()
-> Unsaved Mongoose Instancenew User()
instance of your Mongoose model. The instance is not saved to the database.isNew: true
.const userInstance = User.factory().make();
console.log(userInstance instanceof User); // -> true
console.log(userInstance.isNew); // -> true
// You can now test instance methods, e.g., userInstance.generateAuthToken()
create()
-> Saved Mongoose Documentasync
operation.Promise
containing a saved Mongoose document with isNew: false
.// Create and save a single user
const savedUser = await User.factory().create();
// Create and save 10 users efficiently in batches
const savedUsers = await User.factory(10).create();
.with()
The .with()
method is your tool for precise control over the generated data.
// Override a single attribute
const ceo = User.factory()
.with('name', 'The Big Boss')
.build();
// Override multiple attributes at once by passing an object
const customUser = User.factory()
.with({
name: 'Jane Smith',
email: 'jane.smith@example.com',
age: 42,
})
.build();
// Override nested document attributes
const userWithBio = User.factory()
.with({
profile: {
bio: 'An expert in Mongoose data generation.',
avatar: 'https://i.pravatar.cc/150'
}
})
.build();
To create related documents, the pattern is simple: create the primary document first, then use its _id
when creating the dependent documents.
// Assume a Post model with `author: { type: Schema.Types.ObjectId, ref: 'User' }`
// 1. Create the primary document (the author)
const author = await User.factory().create();
// 2. Create the dependent documents (the posts) and link them
const posts = await Post.factory(3)
.with('author', author._id) // Pass the author's ObjectId
.create();
// Verification
console.log(posts[0].author.toString() === author._id.toString()); // -> true
mongoose-test-factory
automatically generates realistic data for fields with common names. You get sensible data out-of-the-box with zero extra configuration.
Field Name Pattern Contains... | Generated Data Example | Faker.js Method Used |
---|---|---|
name , title , fullName | "Eleanore Glover" | faker.person.fullName |
firstName | "John" | faker.person.firstName |
email | "tavares.forrest@example.org" | faker.internet.email |
password , pwd | "s7@D_9!aB" | faker.internet.password |
username | "john.doe23" | faker.internet.userName |
slug | "a-perfectly-formed-slug" | faker.helpers.slugify |
age | 42 | faker.number.int (realistic range) |
website , url , link | "https://fakerjs.dev" | faker.internet.url |
avatar , imageUrl | "https://avatars.fakerjs.dev/..." | faker.image.avatar |
city , state , country | "New York", "California", "USA" | faker.location.* |
price , cost , amount | 199.99 | faker.commerce.price |
description , content , bio | "A paragraph of lorem ipsum..." | faker.lorem.paragraph |
createdAt , updatedAt | A recent past Date object | faker.date.recent |
birthDate , dob | A Date for an 18-80 year old | faker.date.birthdate |
expiresAt , dueDate | A future Date object | faker.date.future |
uuid , guid | "123e4567-e89b-12d3-a456-426614174000" | faker.string.uuid |
company , organization | "Tech Solutions Inc." | faker.company.name |
productName | "Awesome Steel Keyboard" | faker.commerce.productName |
category | "Electronics" | faker.commerce.department |
...and many more!
YourModel.factory(count?: number): FactoryBuilder
count
(optional): The number of documents to generate. Defaults to 1
.FactoryBuilder
Instance Methods.count(num: number): this
.with(field: string, value: any): this
.with(overrides: object): this
.build(): T | T[]
.make(): T | T[]
.create(): Promise<T | T[]>
FactoryPlugin
Global Object.configure(options: PluginOptions): void
.setLocale(locale: string): void
.setSeed(seed: number): void
.getMetrics(): Record<string, any>
We welcome contributions of all kinds! If you have a feature idea, a bug to report, or want to improve the documentation, please open an issue or submit a pull request.
git checkout -b feature/my-new-feature
).git commit -am 'Add some feature'
).git push origin feature/my-new-feature
).This project is licensed under the MIT License. See the LICENSE file for details.
FAQs
A comprehensive Mongoose plugin for generating realistic test data with schema analysis, factory patterns, and relationship management
We found that mongoose-test-factory demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Detect malware, unsafe data flows, and license issues in GitHub Actions with Socket’s new workflow scanning support.
Product
Add real-time Socket webhook events to your workflows to automatically receive pull request scan results and security alerts in real time.
Research
The Socket Threat Research Team uncovered malicious NuGet packages typosquatting the popular Nethereum project to steal wallet keys.