setting up fake data in mongodb for testing setting up fake data in mongodb for testing mongoose mongoose

setting up fake data in mongodb for testing


You could try to write json files instead of code and use mongoimport to recreate your database.That's easier to maintain than kilometers of very verbose and repetitive code.


I agree with the above solutions and think the best way is to:

  1. Generate fake information using a library tool.
  2. Convert the fake info into a json file.
  3. Upload it onto mongo using mongoimport.

I ound there are libraries out there which allows you to do generate fake data for free such as Faker.js (if you are familiar with node.js and js in general) or you can use the free java version of Faker here: https://github.com/blocoio/faker

I also found a paid solution here: https://www.mockaroo.com/ but don't know why anyone would want to pay for this as it is fairly easy to generate the fake data - here is a step by step guide.

Import the faker java library and the json writer into your project (I'm using gradle so here is the gradle code):

    repositories {        maven { url 'https://jitpack.io' }    }dependencies {    compile 'com.github.blocoio:faker:1.0.1'    compile 'com.googlecode.json-simple:json-simple:1.1.1'}

Use the following java code to generate as many fake objects as you want, here I'm using a loop to generate 3 objects, and save it into a json.file.

public class FakerTest {    static FileWriter file;    public static void main(String[] args) {        try {            file = new FileWriter("c:\\<Your Location>\\test.json"); //try opening the file            for (int i = 0; i < 3; i ++) {                Faker faker = new Faker();                JSONObject obj = new JSONObject();                obj.put("Name", faker.name.firstName());                obj.put("address",faker.address.streetAddress());                obj.put("email",faker.internet.email());                file.write(obj.toJSONString());            }            file.flush();            file.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

Results of the json file:

{"address":"790 Murphy Vista","email":"willa@schmittjenkinsandabernathy.net","Name":"Christop"}{"address":"7706 Larkin River","email":"martin_carter@ryanbartellandeffertz.com","Name":"Braeden"}{"address":"1893 Jamarcus Rest","email":"cassidy_kris@ziemeankundingandblick.com","Name":"Marlee"}

Now, upload it with mongoimport.

The faker library will let you generate lots of fields, please refer to:

https://github.com/stympy/faker/blob/master/README.md


Download this json file provided by MongoDB.

You can mongoimport it using:

mongoimport --db testDB --collection testCollection --file test.json

More details on Mongoimport can be found here.