Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created March 9, 2023 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sibelius/d4f8c0b0a63b0b4480b8cf3edbee499f to your computer and use it in GitHub Desktop.
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
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