Faker.js: How to fake mongodb ObjectId data?

Created on 28 Apr 2015  路  4Comments  路  Source: Marak/faker.js

I am testing my restful apis which use mongodb and express.js. I want to generate some data for my test database in the before hook. However, I cannot find how to generate fake data for ObjectId reference field in the mongodb document.

Or is there any other best practice to test restful apis? Thank you.

Most helpful comment

Are you using mongoose? If yes, try this:

var id = require('mongoose').Types.ObjectId();

All 4 comments

From what I can see, mongoDB:ObjectId is a 12-byte BSON type, constructed using:

a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.

The ObjectId has its own logic, which would need a little bit of time to implement, but if you want to generate 12-byte dumb hex hash, you could write your own function. There are two existing functions that might be interesting in this case:

@chenweiyj would you try to implement this and create a PR?

Are you using mongoose? If yes, try this:

var id = require('mongoose').Types.ObjectId();

@codebien Thank you, this solves my problem.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JeffBeltran picture JeffBeltran  路  5Comments

maticzav picture maticzav  路  3Comments

AlexMiroshnikov picture AlexMiroshnikov  路  4Comments

jnardone picture jnardone  路  6Comments

developdeez picture developdeez  路  5Comments