My API architecture is causing a problem as I try to insert it into an array called items[].
https://i.stack.imgur.com/qe802.png
The setup involves a simple API built on express + mongodb. The challenge lies in figuring out how to store data from the post method in a global array named items[].
https://i.stack.imgur.com/QXKDf.png
Here's the code snippet:
const express = require('express')
const MongoClient = require('mongodb').MongoClient
const ObjectId = require('mongodb').ObjectId
const app = express();
let db;
const port = process.env.PORT || 3015
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.send('Hey')
})
app.get('/artists', (req, res) => {
let count = 10
let page = 0
req.query.count ? count = req.query.count : null
req.query.page ? (page = req.query.page * count, count = page + 5) : null;
db.collection('artists').find().toArray((err, docs) => {
if (err) {
console.log(err)
return res.sendStatus(500)
}
res.send(docs.slice(page, count))
})
}),
app.post('/artists', (req, res) => {
const artist = {
name: req.body.name,
photos: {
small: null,
large: null
},
status: null,
followed: false
}
db.collection('artists').insertOne(artist, (err, result) => {
if (err) {
console.log(err)
return res.sendStatus(500)
}
res.send(artist)
})
})
MongoClient.connect('***********', (err, client) => {
if (err) {
return console.log(err)
}
db = client.db('mongod');
app.listen(port, () => {
console.log(`API is listening on port ${port}...`)
})
})