{"id":27992115,"url":"https://github.com/dirkjbosman/node-mongodb-controllers","last_synced_at":"2026-04-12T18:03:00.757Z","repository":{"id":81074777,"uuid":"291972553","full_name":"dirkjbosman/node-mongodb-controllers","owner":"dirkjbosman","description":"A (Destructured) Express Node MongoDB App w. Controllers \u0026 Mongoose-ORM integration.","archived":false,"fork":false,"pushed_at":"2020-09-12T13:24:12.000Z","size":64,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-08T17:57:21.012Z","etag":null,"topics":["api","express","javascript","mongodb","mongoose","node","nodejs","nosql"],"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/dirkjbosman.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-09-01T10:55:49.000Z","updated_at":"2020-09-12T13:24:14.000Z","dependencies_parsed_at":null,"dependency_job_id":"889ff330-da55-4da1-89de-0007fb952707","html_url":"https://github.com/dirkjbosman/node-mongodb-controllers","commit_stats":null,"previous_names":["dirkjbosman/node-mongodb-controllers"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkjbosman%2Fnode-mongodb-controllers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkjbosman%2Fnode-mongodb-controllers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkjbosman%2Fnode-mongodb-controllers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkjbosman%2Fnode-mongodb-controllers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dirkjbosman","download_url":"https://codeload.github.com/dirkjbosman/node-mongodb-controllers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253124196,"owners_count":21857611,"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":["api","express","javascript","mongodb","mongoose","node","nodejs","nosql"],"created_at":"2025-05-08T17:57:23.663Z","updated_at":"2026-04-10T06:41:34.531Z","avatar_url":"https://github.com/dirkjbosman.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# node-mongodb-controllers\n\nA (Destructured) Express Node MongoDB App w. Controllers \u0026 Mongoose-ORM integration.\n\n### Summary:\n\n- node express server, middleware and apis\n- mongodb non-relational database\n\n### Boilerplates:\n\n- [Part 1: node-postgresql-unstructured](https://github.com/dirkbosman/node-postgresql-unstructured)\n- [Part 2: node-postgresql-destructured](https://github.com/dirkbosman/node-postgresql-destructured)\n- [Part 3: node-postgresql-controllers](https://github.com/dirkbosman/node-postgresql-controllers)\n---\n- [Part 4a: node-mongodb-controllers](https://github.com/dirkbosman/node-mongodb-controllers)\n- Part 4b: Combine [node-mongodb-clientforserver](https://github.com/dirkbosman/node-mongodb-clientforserver) + [node-mongodb-controllers](https://github.com/dirkbosman/node-mongodb-controllers)\n\n### MongoDB \u0026 Mongoose\n\nIf you your Mongo Atlas server ha been corrently set-up (follow the Mongo Atlas Onboarding tut), you can create an `.env`-file with your connection details and try to connect. If you run `npm start` and you get the output below, you have successfully made a connection from your local environment. Note that you might have to set/reset your IP up for this to work (maybe even more than once).\n\n```\n[nodemon] 2.0.4\n[nodemon] to restart at any time, enter `rs`\n[nodemon] watching path(s): *.*\n[nodemon] watching extensions: js,mjs,json\n[nodemon] starting `node server.js`\nconnected\nMongo DB connected cluster0-shard-50-60.xxxx.mongodb.net\n```\n\n### Add Models\n\n```\n# models/User.js\n\nconst mongoose = require('mongoose');\nconst Schema = mongoose.Schema;\n\nconst UserSchema = new Schema({\n  name: {\n    type: String,\n    required: [true, 'Please add a name'],\n    maxlength: [50, 'Only max 50 chars are allowed for the name']\n  },\n  surname: {\n    type: String,\n    required: [true, 'Please add a surname'],\n    maxlength: [50, 'Only max 50 chars are allowed for the surname']\n  },\n  age: {\n    type: Number,\n    max: 120\n  }\n});\n\nmodule.exports = mongoose.model('User', UserSchema);\n```\n\n### Update Controllers\n\n```\n# controllers/users.js\n\nconst User = require('../models/User');\n\nconst getUsers = async (req, res, next) =\u003e {\n  try {\n    const users = await User.find();\n    res.json({ success: true, msg: 'show all users', data: users })\n  } catch(err) {\n    next(err)\n  }\n}\n\nconst getUser = (req, res, next) =\u003e {\n\n};\n\nconst createUser = (req, res, next) =\u003e {\n\n};\n\nconst deleteUser = (req, res, next) =\u003e {\n\n};\n\nconst updateUser = (req, res, next) =\u003e {\n\n};\n\nmodule.exports = {\n  getUsers,\n  getUser,\n  createUser,\n  updateUser,\n  deleteUser\n}\n```\n\nMake request:\n\n- This request should show a JSON with data field with all users: http://localhost:3000/users\n\n### Route to \"Get A User\"\n\n```\nconst getUser = async (req, res, next) =\u003e {\n  // 5f4d75a8bf290843cc1e7f96\n  const { id } = req.params;\n  try {\n    const user = await User.find({ _id: id });\n    res.json({ success: true, msg: 'show selected user', data: user })\n  } catch(err) {\n    next(err)\n  }\n};\n```\n\nMake request:\n\n- http://localhost:3000/\u003cObjectId\u003e should show a JSON with data field with all specific user (i.e. http://localhost:3000/5f4d75a8bf290843cc1e7f96).\n\n### Route to \"Create New User\"\n\n```\nconst createUser = async (req, res, next) =\u003e {\n  try {\n    const { name, surname, age } = req.body;\n    const user = await User.create({ name, surname, age});\n\n    res.json({ success: true, msg: 'show new user', data: user })\n  } catch(err) {\n    next(err)\n  }\n};\n```\n\nTerminal:\n\n```\ncurl -d '{\"name\": \"Jiggly\", \"surname\": \"Puff\", \"age\": 100}' -H \"Content-Type: application/json\" -X POST http://localhost:3000/users\n\ncurl -d '{\"surname\": \"Chu\", \"age\": 100}' -H \"Content-Type: application/json\" -X POST http://localhost:3000/users // prompts error\n\n# Could be denied, because you specified a certain max in your mongoose-schema\ncurl -d '{\"name\": \"Pika\", \"surname\": \"Chu\", \"age\": 140}' -H \"Content-Type: application/json\" -X POST http://localhost:3000/users\n```\n\n### Route to \"Update (Existing) User\"\n\n```\nconst updateUser = async (req, res, next) =\u003e {\n  try {\n    const { id } = req.params;\n    const { name, surname, age } = req.body;\n\n    const user = await User.findByIdAndUpdate(id, { name, surname, age }, { new: true });\n    res.json({ success: true, msg: 'update users', data: user })\n  } catch(err) {\n    next(err)\n  }\n};\n```\n\nTerminal:\n\n```\ncurl -d '{\"name\": \"Pika\", \"surname\": \"Chu\", \"age\": 3}' -H \"Content-Type: application/json\" -X PUT http://localhost:3000/users/5f4f5726ddde594d290c80d1\ncurl -d '{\"name\": \"Jiggly\", \"surname\": \"Puff\", \"age\": 3}' -H \"Content-Type: application/json\" -X PUT http://localhost:3000/users/5f4f5726ddde594d290c80d1\n```\n\n### Route to \"Delete (Existing) User\"\n\n```\nconst deleteUser = async (req, res, next) =\u003e {\n  try {\n    const { id } = req.params;\n\n    const user = await User.findByIdAndDelete(id);\n    res.json({ success: true, msg: `user with id ${id} deleted`, data: user })\n  } catch(err) {\n    next(err)\n  }\n};\n```\n\nTerminal:\n\n```\ncurl -X DELETE http://localhost:3000/users/${id}\ncurl -X DELETE http://localhost:3000/users/5f4d7587bf290843cc1e7f95\n```\n\n#### Connecting two MongoDB-collections\n\nRelationships in the traditional sense don’t really exist in MongoDB like they do in MySQL ([Source](https://vegibit.com/mongoose-relationships-tutorial/)). In other words, related data is not explicitly enforced by MongoDB, but you can map to two (or more) collections. The strategy we will follow for setting up a request to get order from a specific user is, create an `Orders`-model, and then user that order model in the `Users`-controller (and not in the orders' controller).\n\nAfter creating this code, you can go ahead and test it in the browser or in the terminal:\n\n```\ncurl http://localhost:3000/users/5f5004d9713aed0a426bb060 | jq .\ncurl http://localhost:3000/users/5f5004d9713aed0a426bb060/orders | jq .\n```\n\nTo further extend the code, we can also add a filter in the getUserOrders-route to answer this next questions:\n\n- i.e. give me all orders less than 2000 euros\n\nTest it in the terminal:\n\n```\ncurl http://localhost:3000/users/5f5004d9713aed0a426bb060/orders/?price[lte]=2000 | jq .\ncurl http://localhost:3000/users/5f5004d9713aed0a426bb060/orders/?price[gt]=2000 | jq .\n```\n\nAn interesting follow-up question could be: How do you make the connection between `userId` and `_id` and not another collection's `userId` within the same model? Furthermore, if you delete a user_id, what happens with all the records from that userId? i.e. all the orders of that user.\n\n- You don't really define a foreign key in NoSQL normally, but you can if you really want to intercept requests and check if the id is from an existing userId or not, but you would want to do this at the application layer (not db layer). This is one of the difference with explicitly defining a schema vs not.\n- You could think about explicitly defining it in the Mongoose-[schema](https://mongoosejs.com/docs/guide.html), or think about adding another field in the users-collection with name \"active\" and status true or false, and then toggle between them.\n\n\n#### Combine `node-mongodb-clientforserver` and `node-mongodb-controllers`\n\nFor the next step to work, you will need to download, install and initialise both of the two repos separately below. Note, you can combine both in one repo if you wish :)\n\nnode-mongodb-clientforserver\n- Installed axios on client's side to handle apis. Run: `npm i axios`\n- Run server on different port: 3000 and connect\n- Currently I still have the Contentful details to connect to, but you can take that out and purely connect to the mongoDB to extract data from. So you will have to replace the \".env\"-data with connection data to your server and mongodb. \n\nnode-mongodb-controllers\n- Installed cors on server's side, because you want to be able to give cross domain access and accept requests from headers with certain type. Run: `npm i cors`\n- Run server on port: 8000;\n\n\n## Future Suggestions\n\n- We only discusses about connecting collections in the same db, what about if I want to connect collections in two different mongo dbs? i.e. Creating two DBs (`operations` and `analytics`) so you run aggregated queries against your operations into analytics db on a daily, weekly, monthly basis.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdirkjbosman%2Fnode-mongodb-controllers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdirkjbosman%2Fnode-mongodb-controllers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdirkjbosman%2Fnode-mongodb-controllers/lists"}