Mongo.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. const OError = require('@overleaf/o-error')
  2. const { ObjectId } = require('mongodb')
  3. const { ObjectId: MongooseObjectId } = require('mongoose').mongo
  4. function _getObjectIdInstance(id) {
  5. if (typeof id === 'string') {
  6. return ObjectId(id)
  7. } else if (id instanceof ObjectId) {
  8. return id
  9. } else if (id instanceof MongooseObjectId) {
  10. return ObjectId(id.toString())
  11. } else {
  12. throw new OError('unexpected object id', { id })
  13. }
  14. }
  15. function normalizeQuery(query) {
  16. if (!query) {
  17. throw new Error('no query provided')
  18. }
  19. if (
  20. typeof query === 'string' ||
  21. query instanceof ObjectId ||
  22. query instanceof MongooseObjectId
  23. ) {
  24. return { _id: _getObjectIdInstance(query) }
  25. } else if (typeof query._id === 'string') {
  26. query._id = ObjectId(query._id)
  27. return query
  28. } else {
  29. return query
  30. }
  31. }
  32. function normalizeMultiQuery(query) {
  33. if (Array.isArray(query)) {
  34. return { _id: { $in: query.map(id => _getObjectIdInstance(id)) } }
  35. } else {
  36. return normalizeQuery(query)
  37. }
  38. }
  39. function isObjectIdInstance(id) {
  40. return id instanceof ObjectId || id instanceof MongooseObjectId
  41. }
  42. module.exports = {
  43. isObjectIdInstance,
  44. normalizeQuery,
  45. normalizeMultiQuery,
  46. }