Home > database >  mongoose findOne and $push
mongoose findOne and $push

Time:05-02

I am trying to:

1). check to see if the bookId is existing (this bookId is coming for the google books api stored in the book module).

2). if the book is not already in the database then save it.

3). add the id (mongoose.Types.ObjectId) to the User (module) in the 'books' field array.

At the moment i am testing the "push" with static test, it looks like it does not execute the "push" at all. I am a beginner so any help would be very much appreciated.

books: {
    type: Array,
    of: String
  }
bookRouter.post('/book/:id', (req, res, next) => {
  const bookId = req.params.id
  axios
    .get(`https://www.googleapis.com/books/v1/volumes/${bookId}`)
    .then((result) => {
      Book.findOne({ bookId: bookId })
        .then((book) => {
          if (!book) {
            const { title, authors } = result.data.volumeInfo;
            Book.create({
              title, bookId, authors
            })
          }
        })
        .then(() => {
          console.log(req.user.id);
          User.findByIdAndUpdate(req.user.id, { $push: { books: "testing push array" } })
          res.send('success');
        })
    })
    .catch((error) => {
      console.log(error);
      next(error);
    });
});

CodePudding user response:

Book.create is asynchronous and you should await it. You can do

Book.create({}).then(newBook=>console.log(newBook)

The .then that pushes the book to the user array of books should be chained to the Book.create

  • Related