mongoose-mimic
mongoose-mimic is a simple (but powerful) Node.js library to generate test data for Mongoose using only the schema definition.
Features
- Generate random values depending on primitive data types (string, number, boolean, date...)
- Generate random values that meet constraints (uppercase, lowercase, max...)
- Generate custom values for specific fields
- Generate custom values that match non-primitive data types (email, phone, address...)
- Ignore fields
- Generate dates as object or string
Installation
npm install @genially/mongoose-mimic
Usage
mimic(model, opts)
Generates a mimetic document from model
model
: Mongoose schema objectopts
: Generation options, where the options are in the following format:
{
ignore: Array,
applyFilter: Boolean,
returnDate: Boolean,
custom: {
field: {
value: Any,
type: String
}
}
}
Option | Type | Usage |
---|
ignore | Array | It can contains string paths or RegExp of fields to ignore during generation |
applyFilter | Boolean | Apply lowercase, uppercase, and trim filters on generated object if defined in the path |
returnDate | Boolean | Return dates as Date or String |
custom | Object | Special generator for specific fields |
custom.field.value | Any | Predefined value to the given field |
custom.field.type | String | Data type to generate to the given field, in the format: "type.subtype". Examples: "internet.email" or "address.city". See Faker.js methods to know all supported data types |
Usage Example
const mongoose = require('mongoose');
const mimic = require('@genially/mongoose-mimic');
const ignoredFields = ['_id','created_at', '__v', /detail.*_info/];
const genderValues = ['Male', 'Female']
const schemaDefinition = new mongoose.Schema({
name: {
type: String,
required: true,
lowercase: true,
trim: true
},
email: {
type: String,
},
phones: {
type: [String],
}
birth_date: {
type: Date
},
gender: {
type: String,
enum: genderValues
},
data: {
type: Object,
default: null
},
results: [
{
score: Number,
course: Number
}
],
is_student: {
type: Boolean
},
parent: {
type: mongoose.Schema.Types.ObjectId
},
detail: {
main_info: String,
some_info: String,
none_match: String
},
created_at: {
type: Date,
default: Date.now
}
});
const model = mongoose.model('Student', schemaDefinition);
const randomObject = mimic(model, {
ignore: ignoredFields,
returnDate: true,
custom: {
name: {
value: 'Mimic',
},
email: {
type: 'internet.email'
},
phones: {
type: 'phone.phoneNumber'
},
birth_date: {
value: () => new Date('December 25, 1995 23:15:30')
}
}
})
console.log(randomObject);
Testing
To run the test cases use npm test
Related packages
mongoose-mimic API is inspired by mongoose-dummy, which provides a more limited capability to customize generated values.
Other similar packages to generate test data for Mongoose are:
License
Licensed under MIT