I am new to Express and trying to make an app that saves and retrieves user notes in MongoDB by their username. The way I am doing it is by creating an object with the user and saving the notes as an array.
Here is my code in expressJS.
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')
}
})
Here how it looks in MongoDB Compass.
It works, but I don’t think it’s a good solution, as adding, deleting, and editing everything in the array can be cumbersome. Is there a more efficient method for storing data?
2
Answers
Yes you are correct, it is not the best of solutions. While your initial approach works, it can become inefficient as the array grows larger.
MongoDB’s array performance decreases when modifying large arrays, thus updating individual notes within an array can be cumbersome.
A more efficient and scalable solution would be create separate collections for the users and notes, and then create a relationship between the users and the notes collection using a reference to the user (i.e., username or user ID).
This allows MongoDB to efficiently index and query notes, making operations like adding, deleting, or updating specific notes much easier and faster.
Hope this answers your question
So something like
Users
and for Notes
You can now update a single note by it’s respective
_id
and when fetching all notes that belong to a user, you query the notes collection with theuser_id
I think it will need two operation for update a user note, you shouldn’t create new collection for this. mongo db supports array operations, sample is given below
First find the note
You are mixing create and edit note in one route, split it as /create-note and /edit-note
I think this information may help ypu