skip to Main Content

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.
enter image description here

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


  1. 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

    {
      "collection": "users",
      "description": "This collection stores user information.",
      "fields": {
        "_id": {
          "type": "ObjectId",
          "description": "Unique identifier for each user (auto-generated by MongoDB)."
        },
        "username": {
          "type": "String",
          "description": "Unique username for the user."
        },
        "email": {
          "type": "String",
          "description": "Email address of the user (optional)."
        },
        "createdAt": {
          "type": "Date",
          "description": "The date and time when the user account was created."
        }
      },
      "exampleDocument": {
        "_id": "ObjectId('64f7ca1e4f0b8c8d2a9e57e6')",(note that this is the same id of the user document above)
        "username": "Dhruuv70",
        "email": "[email protected]",
        "createdAt": "ISODate('2024-10-25T12:34:56Z')"
      }
    }
    

    and for Notes

    {
      "collection": "notes",
      "description": "This collection stores individual notes. Each note references a user from the 'users' collection by 'user_id'.",
      "fields": {
        "_id": {
          "type": "ObjectId",
          "description": "Unique identifier for each note (auto-generated by MongoDB)."
        },
        "user_id": {
          "type": "ObjectId",
          "description": "Reference to the user who owns the note. This field corresponds to the '_id' field in the 'users' collection."
        },
        "topic": {
          "type": "String",
          "description": "The topic or title of the note."
        },
        "content": {
          "type": "String",
          "description": "The content or body of the note."
        },
        "createdAt": {
          "type": "Date",
          "description": "The date and time when the note was created."
        }
      },
      "exampleDocument": {
        "_id": "ObjectId('74b9ca1e4f0b8c8d2a9e57e7')",
        "user_id": "ObjectId('64f7ca1e4f0b8c8d2a9e57e6')",
        "topic": "hello",
        "content": "world",
        "createdAt": "ISODate('2024-10-25T12:34:56Z')"
      }
    }
    

    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 the user_id

    Login or Signup to reply.
  2. 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

    const data = req.body;
    const note = await Note.findOne({ username 
    });
    await Note.findByIdAndUpdate(note._id, {
     notes: {
      $push: data
     }
    });
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search