Iām a newcomer to Express and currently working on developing an application that can store and retrieve user notes in MongoDB based on their username. My current method involves creating a user object and saving their notes as an array.
Below is the code snippet from my expressJS implementation:
router.post('/editnotes', async (req, res) => {
const data = req.body
const { username } = req.query;
const findUserNotes = await Note.findOne({ username: username })
if (findUserNotes) {
findUserNotes.notes.push(data)
findUserNotes.save()
res.status(201).send('ok here')
}
if (!findUserNotes) {
const note = new Note({
username: username,
notes: [data]
})
await note.save()
res.status(200).send('ok here')
}
})
Shown below is how it appears in MongoDB Compass:
"username": "Dhruv70",
"notes": [
{
"topic": "hello",
"content": "world"
},
{
"topic": "bye",
"content": "universe"
},
{
"topic": "xxxxxxx",
"content": "xx"
}
],
"__v": 31
}
Although the current method works, I believe there could be a more efficient solution for storing and managing data, as performing operations like adding, deleting, or editing elements in the array might become cumbersome over time. Are there any alternative methods worth exploring?