Skip to content

Instantly share code, notes, and snippets.

@patarapolw
Created February 17, 2020 13:49
Show Gist options
  • Save patarapolw/c9fc59e71695ce256b442f36b93fd2dc to your computer and use it in GitHub Desktop.
Save patarapolw/c9fc59e71695ce256b442f36b93fd2dc to your computer and use it in GitHub Desktop.
MongoDB serialize
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