Demo code that excercises MongoDB Create Read Update Delete (CRUD) operations with the mongoose npm module
- /config = mongo connection config (sample)
- /controller = controller code with routes and DB operations in personController.js. and DB setup+purge API in setupController
- model = person DB data model
- /public = cascading stylesheet
- /views = EJS views / HTML UI
- / = app.js main webserver code & package.json
- Add a person - CREATE Crud
- List person(s) - READ cRud
- Update person (needs MongoID from list function) - UPDATE crUd
- Delete person (needs MongoID from list function) - DELETE cruD
purge mongo collection = point browser at http://0.0.0.0:3000/person/purge setup / seed data in collection = http://0.0.0.0:3000/person/setup
See https://docs.mongodb.com/manual/installation/
git clone https://github.com/ajyounguk/mongodb-crud-demo
cd mongodb-crud-demo
npm install
Copy /config/mongo-config-sample.json to mongo-config.json Needs mongo username and password and mongo running with --auth
cp config-sample.json config.json
node app.js
point your browser at the lport 3000 to load Client http://0.0.0.0:3000
This is NOT a hardened/strong security model for mongo, but a simple set of reference creds to get you started:
- Start mongo with no auth model:
mongod
Connect to mongo cli:
mongo
- Create database admin user in mongo cli:
use admin
db.createUser(
{
user: "admin",
pwd: "mypassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
- Restart db with authentication model on:
mongod -- auth
- Connect to mongo cli and login with admin user:
mongo
use admin
db.auth("admin", "mypassword" )
- Create new database (data) and database users PS: if databse does not exist already, it's created
Use data
db.createUser(
{
user: "data_dev",
pwd: "devpassword",
roles: [
{ role: "readWrite", db: "data" }
]
}
)
db.createUser(
{
user: "data_admin",
pwd: "adminpassword",
roles: [
{ role: "dbOwner", db: "data" }
]
}
)
- Create (person) collection in (data) databse
{
Create : "person"
}
- Update the mongo connection configuration file (/config/mongo-config.json). Using the example dev database user above the config file would look like:
{
"mongourl": "mongodb://data_dev:devpassword@127.0.0.1:27017/data"
}
For more information on MongoDB: https://www.mongodb.com/what-is-mongodb
For more information on Express: https://www.npmjs.com/package/express
For more information on Mongoose: https://www.npmjs.com/package/mongoose