Created
March 9, 2023 01:48
-
-
Save sibelius/d4f8c0b0a63b0b4480b8cf3edbee499f to your computer and use it in GitHub Desktop.
transform all ObjectId inside an object to a string to make it easy test assertions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from 'mongoose'; | |
const { ObjectId } = mongoose.Types; | |
// transform all ObjectId to string | |
export const mongooseObjectIdToString = (data: any) => { | |
if (!data) { | |
return data; | |
} | |
if (Array.isArray(data)) { | |
return data.map(d => mongooseObjectIdToString(d)); | |
} | |
if ( | |
ObjectId.isValid(data) && | |
data.toString().indexOf(data) !== -1 | |
) { | |
return data.toString(); | |
} | |
if (typeof data === 'object' && !Array.isArray(data)) { | |
return Object.keys(data).reduce((prev, curr) => ({ | |
...prev, | |
[curr]: mongooseObjectIdToString(data[curr]), | |
}), {}); | |
} | |
return data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment