Created
February 17, 2020 13:49
-
-
Save patarapolw/c9fc59e71695ce256b442f36b93fd2dc to your computer and use it in GitHub Desktop.
MongoDB serialize
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
const cond = { | |
a: new Date(), | |
b: /regexp/gi | |
} | |
const r = JSON.stringify(cond, function (k, v) { | |
const v0 = this[k] | |
if (v0) { | |
if (v0 instanceof Date) { | |
return { $date: v0.toISOString() } | |
} else if (v0 instanceof RegExp) { | |
return { $regex: v0.source, $options: v0.flags } | |
} | |
} | |
return v | |
}) | |
console.log(r) | |
console.log(JSON.parse(r, (_, v) => { | |
if (v && typeof v === 'object') { | |
if (v.$date) { | |
return new Date(v.$date) | |
} else if (v.$regex) { | |
return new RegExp(v.$regex, v.$options) | |
} | |
} | |
return v | |
})) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment