All functions have access to built-in global modules that support common data transformation, encoding, and processing work. You can access the modules in your function source code via global variables specific to each module.
Tip
These global modules are not the same as the Node.js built-in modules. For more information on supported Node.js modules, including how to import them, see Built-in Module Support.
Module | Description |
|---|---|
Methods to read and write JSON Web Tokens. | |
Methods that implement cryptographic algorithms like hashes and signatures. | |
Methods that convert between string and object representations of JSON data. | |
Methods that convert between string and object representations of Extended JSON data. | |
Methods that create Binary JSON objects and convert between various BSON data types and encodings. |
Utilities
JSON Web Tokens (utils.jwt)
You can create and read JSON Web Tokens with
the utils.jwt interface.
Method | Description |
|---|---|
Generates an encoded JSON Web Token string for a given
| |
Decodes the |
utils.jwt.encode()Generates an encoded JSON Web Token string for the
payloadbased on the specifiedsigningMethodandsecret.utils.jwt.encode( signingMethod: string, payload: object, secret: string, customHeaderFields: object ): string ParameterTypeDescriptionsigningMethodstring
The cryptographic algorithm to use when encoding the JWT. Atlas App Services supports the following JWT signing methods:
Signing MethodDescription"HS256"HMAC using SHA-256
"HS384"HMAC using SHA-384
"HS512"HMAC using SHA-512
"RS256"RSASSA-PKCS1-v1_5 using SHA-256
"RS384"RSASSA-PKCS1-v1_5 using SHA-384
"RS512"RSASSA-PKCS1-v1_5 using SHA-512
"ES256"ECDSA using P-256 and SHA-256
"ES384"ECDSA using P-384 and SHA-384
"ES512"ECDSA using P-512 and SHA-512
"PS256"RSASSA-PSS using SHA-256 and MGF1 with SHA-256
"PS384"RSASSA-PSS using SHA-384 and MGF1 with SHA-384
"PS512"RSASSA-PSS using SHA-512 and MGF1 with SHA-512
payloadobject
A JSON object that specifies the token's claims and any additional related data.
secretstring
A secret string that App Services uses to sign the token. The value of the string depends on the signing method that you use:
Signing MethodsDescription"HS256""HS384""HS512"A random string.
"RS256""RS384""RS512"An RSA-SHA private key in PKCS#8 format.
"PS256""PS384""PS512"An RSA-PSS private key in PKCS#8 format.
"ES256""ES384""ES512"An ECDSA private key in PKCS#8 format.
customHeaderFieldsobject
A JSON object that specifies additional fields to include in the JWT's JOSE header.
Returns: A JSON Web Token string encoded for the provided payload.Example
Consider the following JWT claims object:
{ "sub": "1234567890", "name": "Joe Example", "iat": 1565721223187 } We can encode the claims object as a JWT string by calling
utils.jwt.encode(). The following function encodes the JWT using theHS512signing method and the secret"SuperSecret":exports = function() { const signingMethod = "HS512"; const payload = { "sub": "1234567890", "name": "Joe Example", "iat": 1565721223187 }; const secret = "SuperSecret"; return utils.jwt.encode(signingMethod, payload, secret); } "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvZSBTY2htb2UiLCJpYXQiOjE1NjU3MjEyMjMxODd9.-QL15ldu2BYuJokNWT6YRiwZQIiIpvq6Kyv-C6qslNdNiUVxo8zqLJZ1iEkNf2yZKMIrQuMCtIC1tzd2H31AxA"
utils.jwt.decode()Decodes the
payloadof the provided JSON Web Token string. The value ofkeymust correspond to the secret value that was used to encode the JWT string.utils.jwt.decode( jwtString: string, key: string, returnHeader: boolean ): object ParameterTypeDescriptionjwtStringstring
A JSON Web Token string that encodes a set of claims signed with a secret value.
keystring
A string that App Services uses to verify the token signature. The value of the string depends on the signing method that you use:
Signing MethodsDescription"HS256""HS384""HS512"The random string that was used to sign the token.
"RS256""RS384""RS512"The RSA-SHA public key that corresponds to the private key that was used to sign the token.
"PS256""PS384""PS512"The RSA-PSS public key that corresponds to the private key that was used to sign the token.
"ES256""ES384""ES512"The ECDSA public key that corresponds to the private key that was used to sign the token.
returnHeaderboolean
If
true, return the JWT's JOSE header in addition to the decoded payload.acceptedSigningMethodsstring[]
Optional. Array of accepted signing methods. For example,
["PS256", "HS256"]. This argument should be included to prevent against known JWT security vulnerabilities.Returns: If returnHeaderisfalse, returns the decoded EJSON payload.If
returnHeaderistrue, returns an object that contains the JOSE header in theheaderfield and the decoded EJSON payload in thepayloadfield.{ "header": { "<JOSE Header Field>": <JOSE Header Value>, ... }, "payload": { "<JWT Claim Field>": <JWT Claim Value>, ... } } Example
Consider the following signed JWT string:
"eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvZSBTY2htb2UiLCJpYXQiOjE1NjU3MjEyMjMxODd9.-QL15ldu2BYuJokNWT6YRiwZQIiIpvq6Kyv-C6qslNdNiUVxo8zqLJZ1iEkNf2yZKMIrQuMCtIC1tzd2H31AxA" The JWT was signed using the
HS512signing method with the secret value"SuperSecret". We can decode the JWT's claims objectutils.jwt.decode(). The following function decodes the JWT string into an EJSON object:exports = function(jwtString) { const key = "SuperSecret"; return utils.jwt.decode(jwtString, key, false, ["HS512"]); } { "sub": "1234567890", "name": "Joe Example", "iat": { "$numberDouble": 1565721223187 } }
Cryptography (utils.crypto)
You can encrypt, decrypt, sign, and verify data using cryptographic
algorithms with the utils.crypto interface.
Method | Description |
|---|---|
Generates an encrypted text string from a given text string using a specific encryption method and key. | |
Decrypts a provided text string using a specific encryption method and key. | |
Generates a cryptographically unique signature for a given message using a private key. | |
Verifies that a signature is valid for a given message and public key. | |
Generates an HMAC signature from a given input and secret. | |
Generates a hash value for a given input and hash function. |
utils.crypto.encrypt()Generates an encrypted text string from the provided text using the specified encryption method and key.
utils.crypto.encrypt( encryptionType: string, message: string, key: string ): BSON.Binary ParameterTypeDescriptionencryptionTypestring
The type of encryption with which to encrypt the message. The following encryption types are supported:
AES Encryption (
"aes")
messagestring
The text string that you want to encrypt.
keystring
A cryptographic key used to encrypt the text. The key you should use depends on the encryption method:
Encryption TypeEncryption KeyAES
A 16-byte, 24-byte, or 32-byte random string
Returns: A BSON Binary object that contains the text string encrypted with the specified encryption type and key. Example
Assume that we have defined a value named
aesEncryptionKeythat contains the following 32-byte AES encryption key:"603082712271C525E087BD999A4E0738" With this AES key, we can encrypt a message into a base64 string using the following function:
exports = function() { const message = "MongoDB is great!" const key = context.values.get("aesEncryptionKey"); const encryptedMessage = utils.crypto.encrypt("aes", message, key); return encryptedMessage.toBase64(); } "WPBuIvJ6Bity43Uh822dW8QlVYVJaFUiDeUjlTiJXzptUuTYIKPlXekBQAJb"
utils.crypto.decrypt()Decrypts the provided text string using the specified encryption type and key. If both the encryption type and key are the same as those used to encrypt, this returns the original, unencrypted text.
utils.crypto.decrypt( encryptionType: string, encryptedMessage: BSON.Binary, key: string ): BSON.Binary ParameterTypeDescriptionencryptionTypestring
The type of encryption that was used to encrypt the provided text. The following encryption types are supported:
AES Encryption (
"aes")
encryptedMessageA BSON Binary that encodes the encrypted text string that you want to decrypt.
keystring
A cryptographic key used to decrypt the text. The key you should use depends on the encryption type:
Encryption TypeEncryption KeyAES
A 16-byte, 24-byte, or 32-byte random string
Returns: A BSON Binary object that contains the decrypted message. If the provided encrypted message was encrypted with the specified method and key, then the decrypted message is identical to the original message.
Example
Assume that we have defined a Value named
aesEncryptionKeythat contains the following 32-byte AES encryption key:"603082712271C525E087BD999A4E0738" We can use this AES key to decrypt any base64 string that was encrypted with the same key using the following function:
exports = function(encryptedMessage) { // The encrypted message must be a BSON.Binary if(typeof encryptedMessage === "string") { encryptedMessage = BSON.Binary.fromBase64(encryptedMessage) } const key = context.values.get("aesEncryptionKey"); const decryptedMessage = utils.crypto.decrypt("aes", encryptedMessage, key); return decryptedMessage.text(); } "MongoDB is great!"
utils.crypto.sign()Generates a cryptographically unique signature for a message using a private key. The signature can be verified with the corresponding public key to ensure that the signer has access to the private key and that the message content has not been altered since it was signed.
utils.crypto.sign( encryptionType: string, message: string, privateKey: string, signatureScheme: string ): BSON.Binary ParameterTypeDescriptionencryptionTypestring
The type of encryption that was used to generate the private/public key pair. The following encryption types are supported:
RSA Encryption (
"rsa")
messagestring
The text string that you want to sign.
privateKeystring
A private key generated with the specified encryption type.
Important
Key Format
Not all RSA keys use the same format. App Services can only sign messages with a private key that conforms to the standard PKCS#1 format. Private keys in this format have the header
-----BEGIN RSA PRIVATE KEY-----.You can use the following shell script to generate a valid RSA private/public key pair and save each key to its own text file:
Generate an RSA SSH key pair Save the key to a file called `rsa_key` when prompted ssh-keygen -t rsa -m PEM -b 2048 -C "2048-bit RSA Key" Private Key cat rsa_key > rsa.private.txt Public Key ssh-keygen -f rsa_key.pub -e -m pem > rsa.public.txt signatureSchemestring
Optional. Default:
"pss"The padding scheme that the signature should use. App Services supports signing messages with the following schemes:
Probabilistic signature scheme (
"pss")PKCS1v1.5 (
"pkcs1v15")
Returns: A BSON.Binary cryptographic signature for the message signed using the specified private key. Example
Assume that we have defined a value named
rsaPrivateKeythat contains the following RSA private key:-----BEGIN RSA PRIVATE KEY----- MIICXAIBAAKBgQDVsEjse2qO4v3p8RM/q8Rqzloc1lee34yoYuKZ2cemuUu8Jpc7 KFO1+aJpXdbSPZNhGLdANn8f2oMIZ1R9hgEJRn/Qm/YyC4RPTGg55nzHqSlziNZJ JAyEUyU7kx5+Kb6ktgojhk8ocZRkorM8FEylkrKzgSrfay0PcWHPsKlmeQIDAQAB AoGAHlVK1L7kLmpMbuP4voYMeLjYE9XdVEEZf2GiFwLSE3mkJY44033y/Bb2lgxr DScOf675fFUAEK59ATlhxfu6s6rgx+g9qQQ+mL74YZWPqiZHBPjyMRaBalDVC4QF YJ+DopFcB8hY2ElXnbK70ALmVYNjw3RdmC97h0YfOsQcWW0CQQD18aeuPNicVnse Ku22vvhvQYlabaQh4xdkEIxz1TthZj48f61wZwEMipYqOAc5XEtDlNnxgeipv0yF RHstUjwXAkEA3m0Br/U/vC9evuXppWbONana08KLgfELyd3Uw9jG7VKJZTBH5mS8 7CB68aEF8egrJpo8Ss8BkWrvCxYDb4Y77wJAUlbOMZozVtvpKidrIFR9Lho91uWA Hsw9h4W20AzibXBig7SnJ0uE4WMAdS/+0yhgFkceVCmO8E2YW8Gaj4jJjwJASxtg AHy+ItuUEL4uIW4Pn8tVW0BMP3qX0niXyfI/ag/+2S5uePv3V3y4RzNqgH83Yved +FziWKpVQdcTHeuj/QJBAJl1G3WFruk0llIoKKbKljaEiCm1WCTcuEPbdOtkJYvO 9ZYQg/fji70FERkq2KHtY7aLhCHzy0d4n9xgE/pjV+I= -----END RSA PRIVATE KEY----- With this RSA key, we can sign a message using the following function:
exports = function() { const message = "MongoDB is great!" const rsaPrivateKey = context.values.get("rsaPrivateKey"); const signature = utils.crypto.sign("rsa", message, rsaPrivateKey, "pss"); return signature.toBase64(); } "SpfXcJwPbypArt+XuYQyuZqU52YCAY/sZj2kiuin2b6/RzyM4Ek3n3spOtqZJqxn1tfQavxIX4V+prbs74/pOaQkCLekl9Hoa1xOzSKcGoRd8U+n1+UBY3d3cyODGMpyr8Tim2HZAeLPE/D3Q36/K+jpgjvrJFXsJoAy5/PV7iEGV1fkzogmZtXWDcUUBBTTNPY4qZTzjNhL4RAFOc7Mfci+ojE/lLsNaumUVU1/Eky4vasmyjqunm+ULCcRmgWtGDMGHaQV4OXC2LMUe9GOqd3Q9ghCe0Vlhn25oTh8cXoGpd1Fr8wolNa//9dUqSM+QYDpZJXGLShX/Oa8mPwJZKDKHtqrS+2vE6S4dDWR7zKDza+DeovOeCih71QyuSYMXSz+WWGgfLzv/syhmUXP/mjqgLmJU6Kwg5htajDoylpzLC0BLGT4zDZEwBrq/AjwRs/EPjYdFgGCt1WCbbVlDyXvvH1ekDrzACzumhiMSZNNa+ZH3JmMJxTCQWDfiTeAfkauaaZHKIj2q2/QE7vuAhNcVPJ2YgpXnvnQHJpEZBc/Y3Q6JLxom6+cGC4P//9d++r2cwzXIkqD+wSGZVSVtpm5CLtWMRSK5FX2dv16bM+LE8ozoRvtMUDTrQ8SSSDGxyuYbvN9b2fYYPcWpCMchqOBXV6eZGoMldaHX3Qy5h8="
utils.crypto.verify()Checks that the provided signature is valid for the specified message and public key.
If the signature is valid, it guarantees that the signer has access to the corresponding private key and that the message content has not been altered since it was signed.
utils.crypto.verify( encryptionType: string, message: string, publicKey: string, signature: BSON.Binary, signatureScheme: string ): boolean ParameterTypeDescriptionencryptionTypestring
The type of encryption that was used to generate the private/public key pair. The following encryption types are supported:
RSA Encryption (
"rsa")
messagestring
The text string for which you want to verify the signature. If the signature is valid, this is the exact message that was signed.
publicKeystring
The public key for which you want to verify the signature. If the signature is valid, this is the corresponding public key of the private key that was used to sign the message.
Important
Key Format
Not all RSA keys use the same format. App Services can only verify signatures with RSA keys that conform to the standard PKCS#1 format. Public keys in this format have the header
-----BEGIN RSA PUBLIC KEY-----.You can use the following shell script to generate a valid RSA private/public key pair and save each key to its own text file:
Generate an RSA SSH key pair Save the key to a file called `rsa_key` when prompted ssh-keygen -t rsa -m PEM -b 2048 -C "2048-bit RSA Key" Private Key cat rsa_key > rsa.private.txt Public Key ssh-keygen -f rsa_key.pub -e -m pem > rsa.public.txt signatureThe signature that you want to verify.
signatureSchemestring
Optional. Default:
"pss"The padding scheme that the signature uses. App Services supports verifying signatures that use the following schemes:
Probabilistic signature scheme (
"pss")PKCS1v1.5 (
"pkcs1v15")
Returns: A boolean that, if true, indicates whether or not the signature is valid for the provided message and public key.Example
We received a message with a signature in BSON.Binary format and want to verify that the message was signed with the private key that corresponds to the sender's RSA public key:
-----BEGIN RSA PUBLIC KEY----- MIGJAoGBANWwSOx7ao7i/enxEz+rxGrOWhzWV57fjKhi4pnZx6a5S7wmlzsoU7X5 omld1tI9k2EYt0A2fx/agwhnVH2GAQlGf9Cb9jILhE9MaDnmfMepKXOI1kkxDIRT JTuTHn4pvqS2CiOGTyhxlGSiszwUTKWSsrOBKt9rLQ9xYc+wqWZ5AgMBAAE= -----END RSA PUBLIC KEY----- With this RSA key, we can verify a message signed with the correspdoning private key using the following function:
exports = function() { const rsaPublicKey = context.values.get("rsaPublicKey"); const message = "MongoDB is great!" const signature = BSON.Binary.fromBase64("SpfXcJwPbypArt+XuYQyuZqU52YCAY/sZj2kiuin2b6/RzyM4Ek3n3spOtqZJqxn1tfQavxIX4V+prbs74/pOaQkCLekl9Hoa1xOzSKcGoRd8U+n1+UBY3d3cyODGMpyr8Tim2HZAeLPE/D3Q36/K+jpgjvrJFXsJoAy5/PV7iEGV1fkzogmZtXWDcUUBBTTNPY4qZTzjNhL4RAFOc7Mfci+ojE/lLsNaumUVU1/Eky4vasmyjqunm+ULCcRmgWtGDMGHaQV4OXC2LMUe9GOqd3Q9ghCe0Vlhn25oTh8cXoGpd1Fr8wolNa//9dUqSM+QYDpZJXGLShX/Oa8mPwJZKDKHtqrS+2vE6S4dDWR7zKDza+DeovOeCih71QyuSYMXSz+WWGgfLzv/syhmUXP/mjqgLmJU6Kwg5htajDoylpzLC0BLGT4zDZEwBrq/AjwRs/EPjYdFgGCt1WCbbVlDyXvvH1ekDrzACzumhiMSZNNa+ZH3JmMJxTCQWDfiTeAfkauaaZHKIj2q2/QE7vuAhNcVPJ2YgpXnvnQHJpEZBc/Y3Q6JLxom6+cGC4P//9d++r2cwzXIkqD+wSGZVSVtpm5CLtWMRSK5FX2dv16bM+LE8ozoRvtMUDTrQ8SSSDGxyuYbvN9b2fYYPcWpCMchqOBXV6eZGoMldaHX3Qy5h8=") const isValid = utils.crypto.verify("rsa", message, rsaPublicKey, signature, "pss"); return isValid; // true if the signature matches, else false } true
utils.crypto.hmac()Generates an HMAC signature from the provided input and secret. This is useful when communicating with third-party HTTP services that require signed requests.
utils.crypto.hmac( input: string, secret: string, hash_function: string, output_format: string ): string ParameterTypeDescriptioninputstring
The input for which you would like to generate a signature.
secretstring
The secret key to use when generating the signature.
hash_functionstring
The name of the hashing function to use when generating the signature. The following functions are supported:
"sha1","sha256","sha512".output_formatstring
The format of the generated signature. Can be either
"hex"for a hex string, or"base64"for a Base64 string.Returns: The signature of the input, in the format specified by output_format.Example
The following function generates a sha256 signature as a base 64 string:
exports = function() { const signature = utils.crypto.hmac( "hello!", "super-secret", "sha256", "base64" ) return signature } "SUXd6PRMaTXXgBGaGsIHzaDWgTSa6C3D44lRGrvRak0="
utils.crypto.hash()Generates a hash value for the provided input using the specified hash function.
utils.crypto.hash( hash_function: string, input: string | BSON.Binary ): BSON.Binary ParameterTypeDescriptionhash_functionstring
The name of the hashing function. The following functions are supported:
"sha1","sha256","md5".inputstring or BSON.Binary
Required. The input for which you would like to generate a hash value.
Returns: A BSON.Binaryobject that encodes the hash value for the provided input generated by the specified hashing function.Example
The following function hashes an input string with sha256:
exports = function() { return utils.crypto.hash( "sha256", "hello!" ) } "zgYJL7lI2f+sfRo3bkBLJrdXW8wR7gWkYV/vT+w6MIs="
JSON (JavaScript Object Notation)
The JSON global module provides JSON methods to serialize and
deserialize standard JavaScript objects.
Method | Description |
|---|---|
Parse a serialized JSON string into a JavaScript object. | |
Serialize a JavaScript object into a JSON string. |
JSON.parse()Parses the provided JSON string and converts it to a JavaScript object.
JSON.parse(jsonString: string): object ParameterTypeDescriptionjsonStringA serialized string representation of a standard JSON object.
Returns: A standard JavaScript object generated from the provided JSON string. Example
The following function converts a serialized JSON string into an equivalent JavaScript object:
exports = function() { const jsonString = `{ "answer": 42, "submittedAt": "2020-03-02T16:50:24.475Z" }`; return JSON.parse(jsonString); } { "answer": 42, "submittedAt": "2020-03-02T16:50:24.475Z" }
JSON.stringify()Serializes the provided JavaScript object to a JSON string.
JSON.stringify(json: object): string ParameterTypeDescriptionobjectA standard JavaScript Object.
Returns: A string representation of the provided JavaScript object. Example
The following function serializes a JavaScript object into an equivalent JSON string:
exports = function() { const jsonObject = { answer: 42, submittedAt: new Date("2020-03-02T16:46:47.977Z") }; return JSON.stringify(jsonObject); } "{\"answer\":42,\"submittedAt\":\"2020-03-02T16:46:47.977Z\"}"
EJSON (Extended JSON)
The EJSON global module is similar to JSON but
preserves additional Extended JSON type information.
EJSON is a superset of standard JSON that adds additional support for types that are available in BSON but not included in the JSON specification.
Method | Description |
|---|---|
Parse a serialized Extended JSON string into a JavaScript object. | |
Serialize a JavaScript object into an ExtendedJSON string. |
EJSON.parse()Parses the provided EJSON string and converts it to a JavaScript object.
EJSON.parse(ejsonString: string): object ParameterTypeDescriptionejsonString
string
A serialized string representation of an Extended JSON object.
Returns: A JavaScript object representation of the provided EJSON string. Example
The following function converts a serialized EJSON string into an equivalent JavaScript object:
exports = function() { const ejsonString = `{ "answer": { "$numberLong": "42" }, "submittedAt": { "$date": { "$numberLong": "1583167607977" } } }`; return EJSON.parse(ejsonString); } { "answer": { "$numberLong": "42" }, "submittedAt": { "$date": { "$numberLong": "1583167607977" } } }
EJSON.stringify()Serializes the provided JavaScript object to an EJSON string.
EJSON.stringify(json: object): string ParameterTypeDescriptionobjectdocument
An EJSON object. The object may contain BSON types.
Returns: A string representation of the provided EJSON object. Example
The following function serializes a JavaScript object into an equivalent EJSON string:
exports = function() { const jsonObject = { answer: 42, submittedAt: new Date("2020-03-02T16:46:47.977Z") }; return EJSON.stringify(jsonObject); } "{\"answer\":{\"$numberLong\":\"42\"},\"submittedAt\":{\"$date\":{\"$numberLong\":\"1583167607977\"}}}"
BSON (Binary JSON)
The BSON global module allows you to create typed BSON objects and
convert them between various data formats and encodings.
BSON, or Binary JSON, is the data format used internally by MongoDB databases. It encodes a binary representation of document data structures using a superset of the standard JSON types. For more information, refer to the BSON specification.
Type | Description |
|---|---|
Represent an ObjectId value | |
Represent a regular expression | |
Represent a binary data structure | |
Represent a value that compares higher than all other values | |
Represent a value that compares lower than all other values | |
Represent a 32-bit signed integer | |
Represent a 64-bit signed integer | |
Represent a 64-bit floating point number | |
Represent a 128-bit floating point number |
BSON.ObjectId
The BSON.ObjectId type represents a 12-byte MongoDB ObjectId
identifier.
BSON.ObjectId()Constructs a
BSON.ObjectIdobject that encodes an ObjectIdnew BSON.ObjectId(id: string) ParameterTypeDescriptionidstring
Optional. A 12-byte string or a string of 24 hex characters.
Returns: A BSON.ObjectIdobject that encodes the specified ObjectId string or a generatedObjectIdstring if none was specified.Example
const objectId = new BSON.ObjectId("5e58667d902d38559c802b13"); const generatedObjectId = new BSON.ObjectId();
BSON.BSONRegExp
The BSON.BSONRegExp type represents a regular expression. You can use a
BSON.BSONRegExp object with the $regex query operator to
perform a regular expression query on a
MongoDB collection.
BSON.BSONRegExp()Constructs a
BSON.BSONRegExpobject from a regular expression string. You can optionally specify configuration flags.BSON.BSONRegExp(pattern: string, flags: string) ParameterTypeDescriptionpatternstring
A regular expression pattern.
flagsstring
Optional. One or more regular expression flags.
Returns: A BSON.BSONRegExpobject that encodes the provided regular expression pattern and flags.Example
const regex = BSON.BSONRegExp("the great", "ig");
BSON.Binary
The BSON.Binary type represents a binary-encoded data string.
BSON.Binary.fromHex()Constructs a
BSON.Binaryobject from data represented as a hexadecimal string.BSON.Binary.fromHex( hexString: string, subType?: number ): BSON.Binary ParameterTypeDescriptionhexStringstring
A byte aligned string of hexadecimal characters (0-9 and A-F).
subTypeinteger
Optional. The type of data encoded in the hexadecimal string. The value must be in the range 0-255 where
0, the default value, represents a generic binary. For a full list of supported subtypes, refer to the BSON specification.Returns: A BSON.Binaryobject that encodes the provided hexadecimal string.Example
const binary = BSON.Binary.fromHex("54657374206d65737361676520706c656173652069676e6f7265=");
BSON.Binary.prototype.toHex()Converts the
BSON.Binaryobject into a hexadecimal string.BSON.Binary.prototype.toHex(): string Returns: A hexadecimal string representation of the provided BSON.Binaryobject.Example
export = function() { const binary = BSON.Binary.fromHex( "54657374206d65737361676520706c656173652069676e6f7265=" ); const hexString = binary.toHex(); return hexString } "54657374206d65737361676520706c656173652069676e6f7265="
BSON.Binary.fromBase64()Constructs a
BSON.Binaryobject from data represented as a base64 string.BSON.Binary.fromBase64( base64String: string, subType?: number ): BSON.Binary ParameterTypeDescriptionbase64Stringstring
A string of base64 encoded characters.
Note
String Padding
The base64-encoded string must include either one or two equals signs (
=), referred to as "padding", at the end of the string.BSON.Binary.fromBase64()does not support unpadded strings.subTypeinteger
Optional. The type of data encoded in the hexadecimal string. The value must be in the range 0-255 where
0, the default value, represents a generic binary. For a full list of supported subtypes, refer to the BSON specification.Returns: A BSON.Binaryobject that encodes the provided base64 string.Example
const binary = BSON.Binary.fromBase64("VGVzdCBtZXNzYWdlIHBsZWFzZSBpZ25vcmU=");
BSON.Binary.prototype.toBase64()Converts a
BSON.Binaryobject into a base64 string.BSON.Binary.prototype.toBase64(): string Returns: A base64 string representation of the BSON.Binaryobject.Example
const binary = BSON.Binary.fromBase64("VGVzdCBtZXNzYWdlIHBsZWFzZSBpZ25vcmU="); const base64String = binary.toBase64();
BSON.Binary.prototype.text()Converts the
BSON.Binaryobject into a UTF-8 string.BSON.Binary.prototype.text(): string Returns: A UTF-8 string representation of the provided BSON.Binaryobject.Example
const binary = BSON.Binary.fromBase64("VGVzdCBtZXNzYWdlIHBsZWFzZSBpZ25vcmU="); const decodedString = binary.text();
BSON.MaxKey
The BSON.MaxKey type represents a value that compares higher than
all other BSON values.
Example
await collection.findOne({ date: { $lt: BSON.MaxKey } });
BSON.MinKey
The BSON.MinKey type represents a value that compares lower than all
other BSON values.
Example
await collection.findOne({ date: { $gt: BSON.MinKey } });
BSON.Int32
The BSON.Int32 type represents a 32-bit signed integer.
BSON.Long
The BSON.Long type represents a 64-bit signed integer.
BSON.Long(low32, high32)BSON.Long(low32: number, high32: number): BSON.Long Constructs a
BSON.Longobject from two 32-bit integers that represent the low 32 bits and the high 32 bits in the 64-bitLonginteger.ParameterTypeDescriptionlow32integer
Optional. The long integer's 32 low bits. These bits represent the least significant digits of the number.
high32integer
Optional. The long integer's 32 high bits. These bits represent the most significant digits of the number.
Returns: A BSON.Longobject that encodes the specified integer. Returns0if no arguments are supplied.BSON.Longencodes using the following formula:(high32 * (2**32)) + low32 Example
const long = BSON.Long(600206158, 342);
BSON.Double
The BSON.Double type represents a 64-bit (8-byte) floating point
number.
Important
Use Decimal128 for Money
BSON.Double is subject to floating point rounding errors, so it
is not recommended for use cases where decimal values must round
exactly, e.g. financial data. For these cases, use
BSON.Decimal128 instead.
BSON.Double(double)Constructs a
BSON.Doubleobject from a 64-bit decimal value.BSON.Double(double: number): BSON.Double ParameterTypeDescriptiondoublenumber
A 64-bit decimal value.
Returns: A BSON.Doubleobject that encodes the specified double. Returns0if no argument is supplied.Example
const double = BSON.Double(1234.5678);
BSON.Decimal128
The BSON.Decimal128 type represents a 128-bit (16-byte) floating
point number. This type is intended for use cases where decimal values
must round exactly, e.g. financial data.
BSON.Decimal128.fromString(decimalString)Constructs a
BSON.Decimal128from a string representation of a decimal number.BSON.Decimal128(decimalString: string): BSON.Decimal128 ParameterTypeDescriptiondecimalStringstring
A string representing a decimal number, e.g.
"1234.5678910123456".Returns: A BSON.Decimal128that encodes the provided decimal value.Example
const double = BSON.Decimal128.fromString("1234.5678910123456");