Mongo.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 new ObjectId(id)
  7. } else if (id instanceof ObjectId) {
  8. return id
  9. } else if (id instanceof MongooseObjectId) {
  10. return new 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 = new ObjectId(query._id)
  27. return query
  28. } else {
  29. return query
  30. }
  31. }
  32. function normalizeMultiQuery(query) {
  33. if (query instanceof Set) {
  34. query = Array.from(query)
  35. }
  36. if (Array.isArray(query)) {
  37. return { _id: { $in: query.map(id => _getObjectIdInstance(id)) } }
  38. } else {
  39. return normalizeQuery(query)
  40. }
  41. }
  42. function isObjectIdInstance(id) {
  43. return id instanceof ObjectId || id instanceof MongooseObjectId
  44. }
  45. module.exports = {
  46. isObjectIdInstance,
  47. normalizeQuery,
  48. normalizeMultiQuery,
  49. }