This is an easy, basic and raw example of HOW to implement Embedded Documents Relationships (Denormalization) with Mongoose.
For a dryer approach, check Generic Controllers.
- Node 12+
- NPM
- MongoDB
- Mongoose ODM
- Optional: MongoDB account
npm install
npm run dev
npm run build
npm start
- Returns an object with the key data containing an array of objects with
40 records
(max). - Supports query string:
- ?limit=integer
- ?offset=integer
curl http://127.0.0.1:3000/api/artists
{
"data": [
{
"_id": "6206ad6f6dcc7026ff2a19cd",
"name": "Guns N' Roses",
"__v": 0
}
]
}
- Returns the newly created object (aka, artist).
- The server only accepts a payload with the property
name
.
curl -X POST http://127.0.0.1:3000/api/artists -d '{"name":"Green Day"}' -H "Content-Type: application/json"
{
"_id": "6206e65c3d571063b00e9b22",
"name": "Green Day",
"__v": 0
}
- Returns an object with the key data containing an array of objects with
40 records
(max). - Supports query string:
- ?limit=integer
- ?offset=integer
curl http://127.0.0.1:3000/api/songs
{
"data": [
{
"_id": "6206e7f58a567a65fc1553d1",
"name": "Basket Case",
"artist": {
"_id": "6206e65c3d571063b00e9b22",
"name": "Green Day"
},
"__v": 0
}
]
}
- Returns the newly created object (aka, song).
- The server only accepts a payload with the properties
name
andartist
.
IMPORTANT: You have to pass a valid MongoDB ObjectId which should be the _id of an existent artist.
curl -X POST http://127.0.0.1:3000/api/songs -d '{"name":"Basket Case", "artist": "6206e65c3d571063b00e9b22"}' -H "Content-Type: application/json"
{
"_id": "6206e8ec8a567a65fc1553dd",
"name": "Holiday",
"artist": {
"_id": "6206e65c3d571063b00e9b22",
"name": "Green Day"
},
"__v": 0
}
- Any other endpoint will retrieve an object
curl http://127.0.0.1:3000/
{
"message": "Node.js, Express, MongoDB and Mongoose Denormalization!"
}