Git Product home page Git Product logo

mongoose-dummy's Introduction

mongoose-dummy 1.0.4

mongoose-dummy is an automatic dummy object generator for mongoose using only the schema definition built for Node.js.

Installation

  • Latest release:

    npm install mongoose-dummy
    

Usage

dummy(model, opts)

Generates dummy object from model

  • model: Mongoose schema object
  • opts: Generation options, where the options are in the following format:
        {
          ignore: Array,
          autoDetect: Boolean,
          applyFilter: Boolean,
          returnDate: Boolean,
          custom: {
             email: [String, Array, Object],
             phone: [String, Array, Object],
             password: [String, Array, Object]
          }
        }
Option Type Usage
ignore Array It can contains string paths or RegExp of fields to ignore during generation
autoDetect Boolean Attempt to detect e-mail, phone, or password and generate corresponding random data, defaults to true
applyFilter Boolean Apply lowercase, uppercase, and trim filters on generated object if defined in the path
returnDate Boolean Weather to return dates as Date or String
custom Object Special generator for specified fields
custom.email String, Array, or Object String (field to generate a random e-mails), Array of Strings (fields to generate a random e-mail), or Object {field: String or Array of String, value: Function (custom generator function)}
custom.phone String, Array, or Object String (field to generate a random phones), Array of Strings (fields to generate a random phone), or Object {field: String or Array of String, value: Function (custom generator function)}
custom.password String, Array, or Object String (field to generate a random passwords), Array of Strings (fields to generate a random password), or Object {field: String or Array of String, value: Function (custom generator function)}
force Object paths to set it to certain values

dummy.getPaths(model)

Helper function to extract all paths definition from model.

Usage Example

const mongoose = require('mongoose');
const dummy = require('mongoose-dummy');
const ignoredFields = ['_id','created_at', '__v', /detail.*_info/];
let genderValues = ['Male', 'Female']
let schemaDefinition = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        lowercase: true,
        trim: true
    },
    email: {
        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
    }
});
let model = mongoose.model('Student', schemaDefinition);
let randomObject = dummy(model, {
    ignore: ignoredFields,
    returnDate: true
})
console.log(randomObject);

/* Result:
{
    "name": "lyda.renner84",
    "data": {
        "de_AT": {
            "name": "Josianne Bins",
            "email": "[email protected]",
            "phone": "198.514.9229 x60299",
            "posts": [{
                "words": "maxime quia sit",
                "sentence": "Fuga vel in architecto ut modi sequi aliquam debitis.",
                "sentences": "Reprehenderit ratione consequuntu.."
            }, {
                "words": "dignissimos qui qui",
                "sentence": "Eveniet est unde quis sit et ab.",
                "sentences": "Sit eos quaerat aut quisquam unde..",
                "paragraph": "Quasi et numquam cumque neque rerum aliquam ullam.."
            }],
            "address": {
                "geo": {
                    "lat": "25.9144",
                    "lng": "6.0991"
                },
                "city": "Amaraville",
                "state": "Indiana",
                "streetA": "O'Conner Prairie",
                "streetB": "5722 Shane Grove",
                "streetC": "8040 Hane Roads Suite 402",
                "streetD": "Apt. 816",
                "country": "Kenya",
                "zipcode": "74052"
            },
            "website": "garnett.net",
            "company": {
                "bs": "cross-platform facilitate deliverables",
                "name": "Morissette LLC",
                "catchPhrase": "Self-enabling intangible methodology"
            },
            "username": "Emanuel.Botsford37",
            "accountHistory": [{
                "amount": "473.69",
                "date": "2012-02-01T22:00:00.000Z",
                "business": "Lang, Hudson and Heller",
                "name": "Savings Account 3906",
                "type": "invoice",
                "account": "60253551"
            }, {
                "amount": "824.69",
                "date": "2012-02-01T22:00:00.000Z",
                "business": "Rice - Price",
                "name": "Credit Card Account 8924",
                "type": "withdrawal",
                "account": "62599733"
            }]
        }
        }
    },
    "email": "[email protected]",
    "gender": "Male",
    "parent": "59d0ff689b95b02fec446c55",
    "results": [{
        "score": 61,
        "course": 51
    }, {
        "score": 38,
        "course": 63
    }],
    "birth_date": "2017-09-30T14:57:01.279Z",
    "is_student": true,
    "detail": {
        "none_match": "Wade_Robel"
    }
}*/

Testing

To run the test cases use npm test

License

Licensed under MIT

Author

Feel free to Contact us and improve the code.

mongoose-dummy's People

Contributors

ahmed-agiza avatar eomm avatar gundour avatar haiderghaleb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

mongoose-dummy's Issues

Force Options does not work as expected

Hello, option force with more than one property does not work as expected.

When using the force option, in case we force a value to the second property, its value is not
configure correctly.

  describe("regressions", () => {
    it("should force setting be applied to the second property", () => {
      let schemaDefinition = new mongoose.Schema({
        name: {
          type: String,
          required: true,
          lowercase: true,
          trim: true
        },
        email: {
          type: String
        },
        birth_date: {
          type: Date
        },
        parent: {
          type: mongoose.Schema.Types.ObjectId
        }
      });

      const parentId = "5af8a4f33f56930349d8f45b";
      const mongooseDummy = "mongoose-dummy";

      let model = mongoose.model("Student01", schemaDefinition);
      let randomObject = dummy(model, {
        returnDate: true,
        force: {
          parent: parentId,
          name: mongooseDummy // does not work
        }
      });

      expect(randomObject.parent).to.be.equal(parentId);
      expect(randomObject.name).to.be.equal(mongooseDummy); // expected 'mongoose-dummy', but the value is auto generated.
    });
  });

Security updates for dependencies

Hi,
running npm audit on my repository, having mongoose-dummy as a dev dependency, here's the security output:

                                 Manual Review
             Some vulnerabilities require your attention to resolve

          Visit https://go.npm.me/audit-guide for additional guidance


  Moderate        Prototype Pollution

  Package         mpath

  Patched in      >=0.5.1

  Dependency of   mongoose-dummy [dev]

  Path            mongoose-dummy > mongoose > mpath

  More info       https://npmjs.com/advisories/779


  Low             Regular Expression Denial of Service

  Package         debug

  Patched in      >= 2.6.9 < 3.0.0 || >= 3.1.0

  Dependency of   mongoose-dummy [dev]

  Path            mongoose-dummy > mongoose > mquery > debug

  More info       https://npmjs.com/advisories/534

Can you please update the mongoose dependency in order to fix this?
Thank you

Error when using single embed

Throws error when using Mongoose Single Embeds (https://mongoosejs.com/docs/subdocs.html#single-embedded)

let s1 = new mongoose.Schema({
    name : {
        type:String
    }
})

let s2 = new mongoose.Schema({
    name : s1
})
const dummy = require('mongoose-dummy');
let randomObject = dummy(s2)

console.log(JSON.stringify(randomObject));

Error

node_modules/mongoose-dummy/lib/index.js:339
                throw ("Unsupported type " + type)
                ^
Unsupported type embedded

Array within object causes 'force' properties to be ignored

Ok so I've figured out that you need to use dot notation to force nested props, and I've written a random-length loop in my lib to populate arrays, but it's still not picking up arrays WITHIN objects no matter which syntax I try it with. Minimal fail case follows:

const options = {
  ...
  'relationships.parent': '<parent_id>', // this one works
  'relationships.children': [
    '<child_id>',
    '<child_id>',
  ],
  // OR
  'relationships.children.0': '<child_id>',
  'relationships.children.1': '<child_id>',
  // OR
  'relationships.children[0]': '<child_id>',
  'relationships.children[1]': '<child_id>',
}

In both cases above (as well as passing in the fully-structured relationships object), running dummy(Model, options) causes the children to get populated with random strings, not the specific ID strings I'm trying to set them to. All the other fields I'm trying to use this on, including inside top-level arrays, are populated correctly.

Ignore json property

Hi,
let's assume we have a schema object like this:

const MySchema = new mongoose.Schema({
    _id: {
        type: String,
        'default': generate
    },
    name: String,
    surname: String,
    ip: {
        click: String,
        other_click: String,
        many_others: String
    }
});

If I wouldn't to generate the property ip and all sub-parameter.

It would be nice if it will be sufficient to add to the ignore parameter the field ip.* and not all the path (ip.many_others etc..).

I will try to implement this function using regexp:
ignore will be an array of string and/or regexp that, when match, will ignore the field.

What do you think?
Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.