mongoose-model-generator-amcg v1.0.7
Mongoose Model Generator by amcgunagle
Two methods to help you quickly create new files containing Mongoose models.
Installation
npm i mongoose-model-generator-amcg --save-dev
createWorkspace method
Creates a new file with a template for using the modelGenerator.writeModelToNewFile()
method.
Let's say we have the following in myFile.js
:
import modelGenerator from 'mongoose-model-generator-amcg';
modelGenerator.createWorkspace('myNewWorkspace');
Running node myFile.js
would produce a myNewWorkspace.js
file containing the following:
import modelGenerator from 'mongoose-model-generator-amcg';
const properties = ['examplePropertyName-s', 'examplePropertyName2-n-req'];
// Run "node myNewWorkspace.js" to generate a new file with your mongoose model
modelGenerator.writeModelToNewFile(properties);
writeModelToNewFile method
Creates a new file with a Mongoose model. The model's properties are generated from an array of strings passed in as the first argument to this function. You can also pass in the name of both the new model and new file as an optional second argument.
import modelGenerator from 'mongoose-model-generator-amcg';
const userModelProperties = ['email-s-req', 'password-s-req', 'name-s', 'age-n'];
// Run "node (nameOfThisFile).js" to generate a new file with your mongoose model
modelGenerator.writeModelToNewFile(userModelProperties, 'user');
The example above would produce a user.js
file containing the following:
import mongoose from 'mongoose';
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
},
age: {
type: Number,
},
});
const User = mongoose.model('user', UserSchema);
export default User;
String format for creating properties
The strings in the array passed into the writeModelToNewFile
method follow the format of 'nameOfPropety-FirstLetterOfSchemaType'
or 'nameOfPropety-FirstLetterOfSchemaType-req'
.
The SchemaType portion of these strings can be just the first letter of any of the following values: String, Number, Date, Buffer, Boolean, Mixed, ObjectId, Array, Decimal128, Map, Schema
.
The only conflict is Boolean
and Buffer
- since it's likely Boolean
is more commonly used, it is generated from '-b'
while Buffer
is generated from '-bu'
.
Adding '-req'
to any string adds a required: true,
validator for that property.
ES modules
If you get an error using the import-export syntax for ES modules in the examples above, add the following to your package.json file:
{
"type": "module"
}