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.
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.
Most helpful comment
Are you using mongoose? If yes, try this: