0

I have a simple notes app, where I made it possible for adding, deleting a single note and changing importance. But I can't figure out how to make it moving single note up or down; change the order of notes. My approach is to reorder array of current notes and then somehow post or replace existing collection in my database. But I can't find right tool for this. I'm using React, Node.js and MongoDB through Mongoose.

P.S: I googled it, and found nothing relevant to this. But I think it's a simple operation and there should be a function for this in MongoDB.

enter image description here

Here is code from my backend index.js file:

 app.post('/api/notes', (request, response) => {
  const body = request.body;
  if (body.content === undefined) {
    return response.status(400).json({
      error: 'content missing',
    });
  }
  const note = new Note({
    content: body.content,
    important: body.important || false,
    date: new Date(),
  });
  note.save().then((savedNote) => {
    response.json(savedNote);
  });
});

app.get('/api/notes/', (request, response) => {
  Note.find({}).then((notes) => {
    response.json(notes);
  });
});

app.get('/api/notes/:id', (request, response, next) => {
  Note.findById(request.params.id)
    .then((note) => {
      if (note) {
        response.json(note);
      } else {
        response.status(404).end();
      }
    })
    .catch((error) => next(error));
});

app.delete('/api/notes/:id', (request, response, next) => {
  Note.findByIdAndRemove(request.params.id)
    .then((result) => {
      response.status(204).end();
    })
    .catch((error) => next(error));
});

app.put('/api/notes/:id', (request, response, next) => {
  const body = request.body;
    const note = {
    content: body.content,
    important: body.important,
  };
  
  Note.findByIdAndUpdate(request.params.id, note, { new: true })
    .then((updatedNote) => {
      response.json(updatedNote);
    })
    .catch((error) => next(error));
});

Code snippet from frontend:

const App = () => {
  const [notes, setNotes] = useState([]);
  const [newNote, setNewNote] = useState('');
  const [showAll, setShowAll] = useState(true);
  const [errorMessage, setErrorMessage] = useState(null);

  useEffect(() => {
    noteService.getAll().then((initialNotes) => {
      setNotes(initialNotes);
    });
  }, []);

  const addNote = (event) => {
    event.preventDefault();
    const noteObject = {
      content: newNote,
      date: new Date().toISOString(),
      important: Math.random() > 0.5,
      id: notes.length + 1,
    };

    noteService.create(noteObject).then((returnedNote) => {
      setNotes(notes.concat(returnedNote));
      setNewNote('');
    });
  };

  const handleNoteChange = (event) => {
    setNewNote(event.target.value);
  };

  const toggleImportanceOf = (id) => {
    const note = notes.find((n) => n.id === id);
    const changedNote = { ...note, important: !note.important };
    console.log('Changed');
    noteService
      .update(id, changedNote)
      .then((returnedNote) => {
        console.log(returnedNote);
        setNotes(notes.map((note) => (note.id !== id ? note : returnedNote)));
      })
      .catch((error) => {
        setErrorMessage(
          `Note '${note.content}' was already removed from server`
        );
        setTimeout(() => {
          setErrorMessage(null);
        }, 5000);
        setNotes(notes.filter((n) => n.id !== id));
      });
  };
  const delNote = (id) => {
    window.confirm(`Delete this note?`);
    noteService.del(id);
    noteService.getAll().then((initialNotes) => {
      setNotes(initialNotes);
    });
  };

  const moveUp = (id) => {
     const idN = notes.findIndex((n) => n.id === id);
    console.log(idN);

//that's where I reorder my current notes(moving up)
    let updated = [...notes];
    updated.splice(
      idN === 0 ? updated.length - 1 : idN - 1,
      0,
      updated.splice(idN, 1)[0]
    );      
    
  };

  const notesToShow = showAll ? notes : notes.filter((note) => note.important);

And finally code from api (noteService in the code above):

const getAll = () => {
  let request = axios.get(baseUrl);
  return request.then((res) => res.data);
};

const create = (newObject) => {
  const request = axios.post(baseUrl, newObject);
  return request.then((res) => res.data);
};

const update = (id, newObject) => {
  const request = axios.put(`${baseUrl}/${id}`, newObject);
  return request.then((res) => res.data);
};
const del = (id) => {
  axios.delete(`${baseUrl}/${id}`);
};
Sunil Kumar Das
  • 372
  • 1
  • 2
  • 12
Roman
  • 139
  • 8
  • 1
    You shouldn't try to reorder the collection itself, just use `sort` when you query it, and sort by whatever your order criteria is. – Aurast Jan 14 '23 at 15:10
  • @Aurast Ok, but could you say me which request method I have to use for making sorting? Should be put or something else? If put, then in backend it need to be some sort of condition or what? I mean I already have put there and it use Note.findByIdAndUpdate method. I can't grasp this moment. Thanks for your reply – Roman Jan 14 '23 at 17:46
  • 1
    You can sort when you [find()](https://stackoverflow.com/a/54034239/3298338) and when you save a document you can update the sort criteria that's on that document. You're already storing a `date` field with the creation date, so if you want to sort by `important` and `date` then you can do that, or if you want to sort some other way, you can add other fields to the document, whatever you want to sort by. You're thinking about this in terms of "how to move documents" but instead, you should be thinking of it in terms of "what should I sort by". – Aurast Jan 14 '23 at 18:05

0 Answers0