Step 6
Let's implement a method to "update" a note given its ID:
update(id, content, author) {
const index = this.notes.findIndex((note) => note._id === id);
if (index !== -1) {
this.notes[index].content = content;
this.notes[index].author = author;
return this.notes[index];
}
return null;
}
Let's also provide an operation to "delete" a note given its ID:
delete(id) {
const index = this.notes.findIndex((note) => note._id === id);
if (index !== -1) {
const note = this.notes[index];
this.notes.splice(index, 1);
return note;
}
return null;
}
To test our application, update the index.js
where we created sample notes previously to update/delete notes given their id
:
const notes = new NoteDao();
notes.create("Sample 1", "Author 1");
notes.create("Sample 2", "Author 2");
notes.create("Sample 3", "Author 2");
notes.create("Sample 4", "Author 1");
console.log(notes.read(2));
console.log(notes.readAll("Author 1"));
console.log(notes.readAll());
console.log(notes.update(0, "Sample 0", "Author 3"));
console.log(notes.delete(1));
console.log(notes.readAll());
As you save the changes to your file, you must see the sample notes printed to the terminal.
Expected output
Note { content: 'Sample 3', author: 'Author 2', _id: 2 }
[
Note { content: 'Sample 1', author: 'Author 1', _id: 0 },
Note { content: 'Sample 4', author: 'Author 1', _id: 3 }
]
[
Note { content: 'Sample 1', author: 'Author 1', _id: 0 },
Note { content: 'Sample 2', author: 'Author 2', _id: 1 },
Note { content: 'Sample 3', author: 'Author 2', _id: 2 },
Note { content: 'Sample 4', author: 'Author 1', _id: 3 }
]
Note { content: 'Sample 0', author: 'Author 3', _id: 0 }
Note { content: 'Sample 2', author: 'Author 2', _id: 1 }
[
Note { content: 'Sample 0', author: 'Author 3', _id: 0 },
Note { content: 'Sample 3', author: 'Author 2', _id: 2 },
Note { content: 'Sample 4', author: 'Author 1', _id: 3 }
]
Now that we know the NoteDao
works fine, delete all the console.log
message in index.js
and leave it as creating four sample notes.