This is an easy, basic and raw example of HOW to implement Reference Based Relationships (Normalization) 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":"Radiohead"}' -H "Content-Type: application/json"
{
"_id": "6206d43f79e6a14bb0f830d5",
"name": "Radiohead",
"__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": "6206ada46dcc7026ff2a19d1",
"name": "Sweet Child O' Mine",
"artist": {
"_id": "6206ad6f6dcc7026ff2a19cd",
"name": "Guns N' Roses"
}
},
{
"_id": "6206adb26dcc7026ff2a19d3",
"name": "Knockin' On Heaven's Door",
"artist": {
"_id": "6206ad6f6dcc7026ff2a19cd",
"name": "Guns N' Roses"
}
}
]
}
- 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":"No surprises", "artist": "6206d43f79e6a14bb0f830d5"}' -H "Content-Type: application/json"
{
"_id":"6206d51679e6a14bb0f830d7",
"name":"No surprises",
"artist":"6206d43f79e6a14bb0f830d5",
"__v":0
}
- Any other endpoint will retrieve an object
curl http://127.0.0.1:3000/
{
"message": "Node.js, Express, MongoDB and Mongoose Normalization!"
}