Search code examples
mongodbobjectid

How to create new Mongo ObjectId using variable?


Can we add a variable inside ObjectId instead of string?

For example:

const _id = ObjectId(variable);

or:

let variable = '5defabcty1234ds';


{ '$match': { _id: mongoose.Types.ObjectId(variable) } },

Solution

  • Yes, it will create the ObjectID from the string, see the documentation: https://docs.mongodb.com/manual/reference/method/ObjectId/#specify-a-hexadecimal-string

    Edit: The variable will just be replaced to its value (the string) during the execution, so still yes.