{"id":20789269,"url":"https://github.com/samislam/setdoc","last_synced_at":"2025-12-25T02:11:35.793Z","repository":{"id":45673009,"uuid":"513967355","full_name":"samislam/setdoc","owner":"samislam","description":"setDoc is a small and simple utility for querying your database with Mongoose.","archived":false,"fork":false,"pushed_at":"2022-07-31T20:10:18.000Z","size":40,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-21T12:47:53.607Z","etag":null,"topics":["data-fetch","express","express-middleware","express-middlewares","express-mongoose","expressjs-middleware","expressjs-middlewares","fetch-data","mongoose","mongoose-express","mongoose-fetch","mongoose-methods","mongoose-query","mongoose-setdoc","setdoc","setdocmw"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/samislam.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-07-14T16:11:32.000Z","updated_at":"2022-12-11T21:57:42.000Z","dependencies_parsed_at":"2022-09-26T21:30:16.032Z","dependency_job_id":null,"html_url":"https://github.com/samislam/setdoc","commit_stats":null,"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samislam%2Fsetdoc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samislam%2Fsetdoc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samislam%2Fsetdoc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/samislam%2Fsetdoc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/samislam","download_url":"https://codeload.github.com/samislam/setdoc/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243134695,"owners_count":20241832,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["data-fetch","express","express-middleware","express-middlewares","express-mongoose","expressjs-middleware","expressjs-middlewares","fetch-data","mongoose","mongoose-express","mongoose-fetch","mongoose-methods","mongoose-query","mongoose-setdoc","setdoc","setdocmw"],"created_at":"2024-11-17T15:22:02.433Z","updated_at":"2025-12-25T02:11:30.770Z","avatar_url":"https://github.com/samislam.png","language":"JavaScript","readme":"**setDoc** is a small and simple utility for querying your database with Mongoose.\n\n# Quick Overview 🍇:\n\n**setDoc** can be used as an express middleware, for example:\n\n```js\napp.get(\n  '/users',\n  setDocMw((req) =\u003e UserModel.find({}), { propName: '$users' }),\n  (req, res, next) =\u003e {\n    // use it as req.$users here\n  }\n)\n```\n\n**setDoc** can also be used as a regular JavaScript function, for example:\n\n```js\napp.get(\n  '/users',\n  expressAsyncHandler(async (req, res, next) =\u003e {\n    const users = await setDoc(UserModel.find({}))\n    // users is the database response for calling UserModel.find({})\n  })\n)\n```\n\nor quickly set the doc and send the response:\n\n```js\napp.get(\n  '/users',\n  sendDocMw((req) =\u003e UserModel.find({}))\n)\n```\n\n# Examples: 🍎\n\n### Example #1:\n\n```js\nconst express = require('express')\nconst expressAsyncHandler = require('express-async-handler')\nconst app = express()\nconst { setDoc, setDocMw, sendDocMw } = require('setDoc')\nconst { UserModel } = require('./models/UserModel')\n\napp.use(express.json())\n\napp.route('/api/users').get(\n  setDocMw((req) =\u003e UserModel.find({}, { propName: 'docs' })),\n  (req, res, next) =\u003e {\n    res.status(200).json({ data: req.docs })\n  }\n)\napp\n  .route('/api/users/:id')\n  .get(sendDocMw((req) =\u003e UserModel.findById(req.params.id)))\n  .patch(\n    expressAsyncHandler(async (req, res, next) =\u003e {\n      const doc = await setDoc(() =\u003e UserModel.findByIdAndUpdate(req.params.id, req.body))\n      res.status(200).json({\n        data: doc,\n      })\n    })\n  )\napp.use((err, req, res, next) =\u003e {\n  if (err.name === 'setDocNotFoundError') {\n    res.status(err.statusCode).json({\n      message: err.message,\n    })\n  }\n})\napp.listen(3000, () =\u003e console.log('listening on port 3000...'))\n```\n\n### Example #2:\n\n```js\napp.get(\n  '/channels/:channelId',\n  setDocMw(UserModel.find({}), (req) =\u003e ({\n    post(doc) {\n      console.log(doc)\n      // {\n      //   name: 'Kids Playhouse!',\n      //   email: 'kids@kidi.com',\n      //   subscribers: [\n      //     {\n      //       id: 1,\n      //       name: 'Murat',\n      //     },\n      //     {\n      //       id: 2,\n      //       name: 'Omer',\n      //     },\n      //     {\n      //       id: 3,\n      //       name: 'Yaser',\n      //     },\n      //   ]\n      // }\n      return doc.subscribers\n    },\n  })),\n  (req, res, next) =\u003e {\n    console.log(req.mainDocs)\n    // [\n    //   {\n    //     id: 1,\n    //     name: 'Murat',\n    //   },\n    //   {\n    //     id: 2,\n    //     name: 'Omer',\n    //   },\n    //   {\n    //     id: 3,\n    //     name: 'Yaser',\n    //   },\n    // ]\n  }\n)\n```\n\n# API: 🥥\n\n# `setDoc(query: function, options: object)`: Promise\n\na JavaScript function, queries your database, then returns the resolved value of the query.\n\n\u003cins\u003eparameters:\u003c/ins\u003e\n\n- **query**: _function_, ex: `setDoc((req)=\u003eUserModel.find())`.\n  - it's important to point out that you must leave the query as it is without awaiting it, awaiting it is the job of **setDoc** itself.\n  - Your function will be called without arguments.\n  - Your function must return a mongoose query.\n- **options**: _object_, options to configure how setDoc works.\n  - **notFoundErr**: _boolean_, throw an error when the database query returns undefined (default: **true**).\n    - a _not found document_ is only considered not found if they query returned undefined.\n  - **notFoundMsg**: _any_, the message to display in the error when a requested document is not found (default: \\*\"**The resource you requested was not found\"\\***).\n  - **notFoundStatusCode**: _number_, the status code in the error to have when a document is not found (default: **404**).\n\n# `setDocMw(query: function , options: object | function)`: express middleware\n\nan ExpressJs middleware, queries your database, then sets the resolved value of the query on the express `req` object with the property name you specify, which can be then accessed for example as `req.mainDoc` or `req.mainDocs`.\n\n\u003cins\u003eparameters:\u003c/ins\u003e\n\n- **query:** *function*, ex: `setDocMw((req)=\u003eUserModel.find())`.\n  - it's important to point out that you must leave the query as it is without awaiting it, awaiting it is the job of **setDoc** itself.\n  - Your function will be called with the express `req` object as the first argument.\n  - Your function must return a mongoose query.\n- **options:** *object |* _function_, options to configure how setDocMw works.\n  - If you provided a function, your function will be called with the `req` object.\n  - Your function must return an object, ex: `(req) =\u003e ({ options-here })`.\n    - **notFoundErr**: _boolean_, consider it an error when the database query returns undefined (default: **true**).\n      - a _not found document_ is only considered not found if the resolved value of the query was undefined.\n    - **notFoundMsg**: _any_, the message to display in the error when the database query returns undefined (default: _\"**The resource you requested was not found**\"_).\n    - **notFoundStatusCode**: _number_, the status code to have in the error when the database query returns undefined (default: **404**).\n    - **handleNotFoundError**: _boolean_, send the meaningful response if a requested document wasn't found, if set to false, `next()` is called with a *setDocNotFoundError* error (default: **true**).\n    - **callNext**: _boolean_,call `next()` as the last step.\n      - set to **true** only if you have middlewares to execute after this one.\n    - **propName**: _string_, the property name to set on the request object (default: **undefined**).\n      - if this property is set, the options _ifSinglePropName_ and _ifMultiPropName_ will be ignored.\n    - **ifSinglePropName**: _string_, the property name to set on the request object if the resolved value of the query wasn't an array (default : '**mainDoc**').\n    - **ifMultiPropName**: _string_, the property name to set on the request object if the resolved value of the query was an array (default: '**mainDocs**').\n\n# `sendDocMw(query: function , options: object | function)`: express middleware\n\nan ExpressJs middleware, queries your database, then sends the resolved value of the query directly using the [sendRes](https://www.npmjs.com/package/@samislam/sendres) package with the options you specify.\n\n\u003cins\u003eparameters:\u003c/ins\u003e\n\n- **query:** *function*, ex: `sendDocMw((req)=\u003eUserModel.findById(req.params.id))`.\n\n  - it's important to point out that you must leave the query as it is without awaiting it, awaiting it is the job of **setDoc** itself.\n  - Your function will be called with the express `req` object as the first argument.\n  - Your function must return a mongoose query.\n\n- **options:** *object |* _function_, options to configure how setDocMw works.\n  - If you provided a function, your function will be called with the `req` object.\n  - Your function must return an object, ex: `(req) =\u003e ({ options-here })`.\n    - **notFoundErr**: _boolean_, consider it an error when the database query returns undefined (default: **true**).\n      - a _not found document_ is only considered not found if the resolved value of the query was undefined.\n    - **notFoundMsg**: _any_, the message to display in the error when the database query returns undefined (default: _\"**The resource you requested was not found**\"_).\n    - **notFoundStatusCode**: _number_, the status code to have in the error when the database query returns undefined (default: **404**).\n    - **handleNotFoundError**: _boolean_, send the meaningful response if a requested document wasn't found, if set to false, `next()` is called with a *setDocNotFoundError* error (default: **true**).\n    - **callNext**: _boolean_,call `next()` as the last step.\n      - set to **true** only if you have middlewares to execute after this one.\n    - **statusCode**: _number_, the status code for the response on the success of the operation (default **200**).\n    - **resBody**: _function_, a function that gets called with the resolved value of the database query, in this function, you must return an object, this object is what your response body is going to hold.\n    - **sendRes**: _object_, the options you want to pass to the sendRes package, for these options, read them on the official docs of [sendRes](https://www.npmjs.com/package/@samislam/sendres).\n\n# Error Handling: 🍅\n\nThere are two types of errors that could happen in the context of setDoc:\n\n1.  **Mongoose Error**, ex: Cast errors, duplicate fields errors, validation errors.\n    - for handling these errors, you should read [the Mongoose official docs](https://mongoosejs.com/).\n2.  **setDoc Error**, and there's only one error type that setDoc has, which is the _setDocNotFoundError_,this error happens when a user is trying to query the database for a record that's just not there.\n    - For `setDoc()`, it throws the error, which you may handle then using a try/catch blocks, [await-to](https://www.npmjs.com/package/await-to-js), or simply just an express error-handling middleware.\n    - For `setDocMw()`, it sends the error automatically, however, you can disable that behavior, using the `handleNotFoundError` option.\n\nTo handle the error, the error has the following properties:\n\n- `name`: **setDocNotFoundError**.\n- `message`: (default _\"**The resource you requested was not found**\"_).\n- `statusCode`: the status code chosen when the database query returns undefined (default: **404**).\n- `stack`: the call stack for the error.\n\nFor example, if you want to handle a setDoc() function not found error:\n\n```js\ntry {\n  const doc = await setDoc(Model.findOne({ email: 'murat@email.com' }))\n} catch (error) {\n  console.log(error)\n  //   {\n  //     name: 'setDocNotFoundError',\n  //     message: \"The resource you requested was not found\"\n  //     statusCode: 404,\n  //     stack: ...the error stack\n  //   }\n  // --- then send the response with the error\n}\n```\n\nBut normally, you wouldn't bother adding try/catch blocks around your code, because you're must likely going to have this code in an express middleware, you can use an npm package like [express-async-handler](https://www.npmjs.com/package/express-async-handler) for that, ex:\n\n```js\napp.get(\n  expressAsyncHandler(async (req, res, next) =\u003e {\n    const doc = await setDoc(Model.findOne({ email: 'murat@email.com' }))\n    // the rest of your code normally\n  })\n)\n```\n\nIn this example, if setDoc throws an error, the **expressAsyncHandler** middleware is going to capture that error and will call next with the thrown error directly, ex:\n\n```js\napp.use((err, req, res, next) =\u003e {\n  if (err.name === 'setDocNotFoundError') {\n    res.status(err.statusCode).json({\n      status: 'fail',\n      message: err.message,\n    })\n  }\n})\n```\n\n# FAQ: 🍉\n\n**Q**: Is there any way I can prevent `setDocMw()`/`sendDocMw()` from sending the error? what if I wanted to handle that error myself?\n\n- Use the `handleNotFoundError` option and set it to false, this way, `setDocMw()` or `sendDocMw()` will call `next()` with the error.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamislam%2Fsetdoc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsamislam%2Fsetdoc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsamislam%2Fsetdoc/lists"}