Step 6
Let's update the NoteDao.js
file accordingly. First, add the following import statement:
const mongoose = require("mongoose");
Next, update the create
method:
- async create({ title, text }) {
+ async create({ title, text, author }) {
if (title === undefined || title === "") {
throw new ApiError(400, "Every note must have a none-empty title!");
}
if (text === undefined) {
throw new ApiError(400, "Every note must have a text attribute!");
}
+ if (!author || !mongoose.isValidObjectId(author)) {
+ throw new ApiError(400, "Every note must have an author!");
+ }
- const note = await Note.create({ title, text });
+ const note = await Note.create({ title, text, author });
return note;
}
Then, update the readAll
method:
// returns an empty array if there is no note in the database
// for the given author or no note matches the search query
async readAll(author, query = "") {
if (!author || !mongoose.isValidObjectId(author)) {
throw new ApiError(500, "Author attribute was is invalid or missing!");
}
const notes = await Note.find({ author });
if (query !== "") {
return notes.filter(
(note) => note.title.includes(query) || note.text.includes(query)
);
}
return notes;
}
Notice we expect an author parameter; if not provided (or invalid), we throw "Internal Server Error" (code 500).
Next, update the read
method:
async read(author, id) {
const note = await Note.findById(id);
if (!author || !mongoose.isValidObjectId(author)) {
throw new ApiError(500, "Author attribute was is invalid or missing!");
}
if (note === null) {
throw new ApiError(404, "There is no note with the given ID!");
}
if (note.author.toString() !== author) {
throw new ApiError(
403,
"You are not authorized to access this resource!"
);
}
return note;
}
Notice we made a change to return 404 if a document with the given ID does not exist.
Next, change the update
method:
async update(author, id, { title, text }) {
await this.read(author, id);
return Note.findByIdAndUpdate(
id,
{ title, text },
{ new: true, runValidators: true }
);
}
Finally, update the delete
method:
async delete(author, id) {
await this.read(author, id);
return Note.findByIdAndDelete(id);
}
Notice the update
and delete
methods rely on the read
method.