Advanced modeling with mongoose.
Fill mongoose schema with easy types and seed mongoose model by fake data.
$ npm install mongoose-easy-types
//Instead of this
var schema = mongoose.Schema({
firstName : {
type : mongoose.Schema.Types.String
},
dateOfBirth : {
type : mongoose.Schema.Types.Date
},
price : {
type : mongoose.Schema.Types.Number
},
email : {
type : mongoose.Schema.Types.String,
required: true
},
gender : {
type : mongoose.Schema.Types.Boolean,
default: false
}
});
//write this
var schema = mongoose.Schema({
firstName : Types.name.firstName({}),
date : Types.date.future(),
price : Types.commerce.price(),
email : Types.internet.email({required: true}),
gender : Types.random.boolean({default: true })
});
var mongoose = require('mongoose');
var Types = require('mongoose-easy-types').Types;
var Plugin = require('mongoose-easy-types').Plugin;
// register plugin globally (or on any schema you want to)
mongoose.plugin(Plugin)
var schema = mongoose.Schema({
firstName : Types.name.firstName({}),
lastName : Types.name.firstName({require : true})
date : Types.date.future(),
price : Types.commerce.price(),
email : Types.internet.email({required: true}),
gender : Types.random.boolean({default: false}),
image : Types.image.imageUrl(),
peoples : [{
name : Types.name.findName({}),
date : Types.date.future()
}]
});
var Model = mongoose.model('Model', schema);
// seed database with 20 fake items of type 'Model'
Model.seed(20, callback);
var mongoose = require('mongoose');
var Plugin = require('mongoose-easy-types').Plugin;
var Types = require('mongoose-easy-types').Types;
// register plugin globally (or on any schema you want to)
mongoose.plugin(Plugin)
var schema = mongoose.Schema({
firstName : {
type : Types.name.firstName().type,
fakePath : Types.name.firstName().fakePath
},
age : {
type : Types.random.number().type,
fakePath : Types.random.number().fakePath
},
gender : {
type : Types.random.boolean().type,
fakePath : Types.random.boolean().fakePath,
default : false
}
});
Model = mongoose.model('Model', schema);
Model.fake(10, callback); //return a list of model instances, filled with fake values
var mongoose = require('mongoose');
var Plugin = require('mongoose-easy-types').Plugin;
var Types = require('mongoose-easy-types').Types;
var schema = mongoose.Schema({
firstName : {
type : Types.name.firstName().type,
fakePath : Types.name.firstName().fakePath
},
age : Types.random.number(),
gender : {
type : Types.random.boolean().type,
fakePath : Types.random.boolean().fakePath,
default : false
}
});
// register plugin into schema
schema.plugin(Plugin);
Model = mongoose.model('Model', schema);
var item = new Model();
item.fake(); // fill all fields with fake values
// or
item.fake(['firstName', 'age']); // fill only 'firstName' and 'age' with fake values
console.log(item.firstName);
// output: John
console.log(item.age);
// output: 21