controller.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict'
  2. const DataModel = require('./model')
  3. // Data controller
  4. module.exports = {
  5. Model: DataModel,
  6. /**
  7. * Add a document
  8. * @param {Object} dataObj The new data document (only the data property!)
  9. * @returns {Promise<Object>} The newly inserted document
  10. */
  11. async add(dataObj) {
  12. const doc = await DataModel.create({ data: dataObj })
  13. console.log(`New document was added. id=${doc.id}`)
  14. return doc
  15. },
  16. /**
  17. * Delete a document
  18. * @param {String} dataId The _id of the document to delete
  19. * @returns {Promise<void>} The document was deleted
  20. */
  21. async del(dataId) {
  22. const doc = await DataModel.findByIdAndDelete(dataId)
  23. console.log(`A document was deleted. id=${doc.id}`)
  24. },
  25. /**
  26. * Update a document
  27. * @param {String} dataId The _id of the document to update
  28. * @param {Object} newDataObj The new data content of the document (only the data property!)
  29. * @returns {Promise<Object>} The newly updated document
  30. */
  31. async update(dataId, newDataObj) {
  32. const doc = await DataModel.findByIdAndUpdate(dataId, { $set: { data: newDataObj } }, { new: true })
  33. console.log(`A document was updated. id=${doc.id}`)
  34. return doc
  35. },
  36. /**
  37. * Find a document
  38. * @param {String} dataId The _id of the document to find
  39. * @returns {Promise<Object>} The found document
  40. */
  41. findId(dataId) {
  42. return DataModel.findById(dataId)
  43. },
  44. find: DataModel.find,
  45. /**
  46. * Find data by any application parameter
  47. * @param {Object} obj Application properties
  48. * @param {String} [obj.msgId] Message ID (type of message)
  49. * @param {String} [obj.uuid] Unique uuid
  50. * @param {String} [obj.experimentName] Experiment name
  51. * @param {String} [obj.sceneName] Scene name
  52. * @param {String} [obj.userId] User ID
  53. * @param {String} [obj.experimentId] Experiment ID
  54. * @returns {Promise<Object[]>} Database query result
  55. */
  56. findCustom({ msgId, uuid, experimentName, sceneName, userId, experimentId }) {
  57. let search = {}
  58. if (msgId) search['data.msgId'] = msgId
  59. if (uuid) search['data.uuid'] = uuid
  60. if (experimentName) search['data.msg.experimentName'] = experimentName
  61. if (sceneName) search['data.msg.sceneName'] = sceneName
  62. if (userId) search['data.userId'] = userId
  63. if (experimentId) search['data.experimentId'] = experimentId
  64. return DataModel.find(search)
  65. }
  66. }