Step 24: Bookmark DAO with Mongoose ODM
Update the src/data/BookmarkDAO.js
file:
import Bookmark from "../model/Bookmark.js";
class BookmarkDAO {
// return the created bookmark
async create({ title, url }) {
const bookmark = await Bookmark.create({ title, url });
return bookmark;
}
// return all bookmarks
async readAll({ title, url }) {
const filter = {};
if (title) {
filter.title = title;
}
if (url) {
filter.url = url;
}
const bookmarks = await Bookmark.find(filter);
return bookmarks;
}
// return the bookmark with the given id
// return null if id does not exist in our database
async read(id) {
const bookmark = await Bookmark.findById(id);
return bookmark;
}
// return the updated bookmark
// return null if id does not exist in our database
async update({ id, title, url }) {
const bookmark = await Bookmark.findByIdAndUpdate(
id,
{ title, url },
{ new: true, runValidators: true }
);
return bookmark;
}
// return the deleted bookmark
// return null if id does not exist in our database
async delete(id) {
const bookmark = await Bookmark.findByIdAndDelete(id);
return bookmark;
}
}
export default BookmarkDAO;
Notes:
- The
create
method allows you to create documents of that model. As an argument, it takes an object representing the data to be saved in the database. It throws an error if it encounters any errors while creating a document. - The
find
method takes an optional parameter, a filter, which can be used to search for notes that match the given attribute values. If we want to receive all notes, we can callfind
with no argument or with an empty filter object. - If there are no "bookmarks" in the database, or there is no match for the filter we have provided, the
find
method returns an empty array. - The first argument to
findByIdAndUpdate
is the ID of a bookmark in our database to be updated. Ifid
does not match an existing bookmark, thefindByIdAndUpdate
will returnnull
. - The second argument to
findByIdAndUpdate
is an object containing the new attributes (and their values) which are to replace the existing attribute values of the bookmark to be updated. If any of these are undefined, the attribute will not change (so we don't need if statements to guard against this scenario) - The third argument to
findByIdAndUpdate
is an “option” object. The first option isnew: true
which changes the default behavior offindByIdAndUpdate
to return the updated note (instead of the original one). The second option isrunValidators: true
that changes the default behavior offindByIdAndUpdate
to force running validators on new attributes. If validation fails, thefindByIdAndUpdate
operation throws an error. - The
findByIdAndDelete
will delete and return the deleted note if theid
exists in the database. Otherwise, it will returnnull
.