user1177440
user1177440

Reputation:

Mongoose ObjectId : Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

I am having difficulty creating my own ObjectId. I have two models:

const TableSchema = new mongoose.Schema ({ 
  .... 
  chairs: [{type: mongoose.Schema.Types.ObjectId, ref: 'ChairModel}] 
  .... 
}) ;


const ChairSchema = new mongoose.Schema ({ 
 .... 
 table: {type: mongoose.Schema.Types.ObjectId, ref: 'TableModel} 
 .... 
 }) ;

This pattern works for me ever time, when ObjectId is generated by mongoose.

But when I generate a randomAlphaNum string:

let randomNum = makeRandom(24); //  1etdk0c86762e0fb12dptsli
let TableId = mongoose.Types.ObjectId(randomNum);

I generate the error:

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters

How can I create a valid mongoose ObjectId from a simple alphaNumeric script generator?

Upvotes: 2

Views: 1809

Answers (1)

ema
ema

Reputation: 5773

ObjectIds must be composed of valid Hex values (you have p, t and s). One option (I don't know which library are you using for makeRandom) is to restrict the characters set of makeRandom to 0-9 a-f. Otherwise, if they are random you can let mongoose to generate ids for you:

let tableId = mongoose.Types.Objec‌​tId()

Upvotes: 1

Related Questions