Use firebase Auth uid as user document _id in mongoDB

Viewed 896

I have user collection and want to use Firebase uid as document _id ,

let _id = new ObjectID('Firebase Auth uid'); // Error Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex
  let val = Object.assign(req.body, {
       _id: _id,
  });
  const user = new User(val);

  // Save User in the Collection
  return user.save();

Eg: Firebase Uid = 5w9WnBiUPdT2wh7bsarYBQLQDqa2

And if i pass directly without using new ObjectID('Firebase Auth uid'); mongoose returns

Failed: _id: Cast to ObjectID failed for value "ThobO6kTv6aMHUa4UN3nBjkCgNb2" at path "_id"

1 Answers

An ObjectID is a 24-byte value, the constructor expects a hexadecimal string.

If you plan to use strings for _id values, explicitly declare _id as String in the schema.

    const schema = new mongoose.Schema({
      _id: String
    });
Related