From 8ce85cc79015b0b7582d179bb5b10b7b252a1a8e Mon Sep 17 00:00:00 2001 From: AdithyakrishnaV Date: Fri, 2 Jul 2021 07:30:46 +0530 Subject: [PATCH] add $addToSet operator --- index.js | 51 +++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index 9997dc7..c25323e 100644 --- a/index.js +++ b/index.js @@ -272,22 +272,53 @@ Access Public Parameter isbn Method PUT */ -booky.put("/book/update/author/:isbn/:authorId", (req, res) => { +booky.put("/book/update/author/:isbn", async (req, res) => { //update book database - database.books.forEach((book) => { - if (book.ISBN === req.params.isbn) { - return book.author.push(parseInt(req.params.authorId)); + + const updatedBook = await BookModel.findOneAndUpdate({ + ISBN: req.params.isbn + }, + { + $addToSet: { + authors: req.body.newAuthor } - }); + }, + { + new: true, + } + ); + // database.books.forEach((book) => { + // if (book.ISBN === req.params.isbn) { + // return book.author.push(parseInt(req.params.authorId)); + // } + // }); // update author database + + const updatedAuthor = await AuthorModel.findOneAndUpdate( + { + id: req.body.newAuthor + }, + { + $addToSet: { + books: req.params.isbn + } + }, + { + new: true + } + ); - database.author.forEach((author) => { - if (author.id === parseInt(req.params.authorId)) - return author.books.push(req.params.isbn); - }); + // database.author.forEach((author) => { + // if (author.id === parseInt(req.params.authorId)) + // return author.books.push(req.params.isbn); + // }); - return res.json({ books: database.books, author: database.author }); + return res.json( + { books: updatedBook, + author: updatedAuthor, + message: "New author was added" + }); }); /*