猫鼬 findOne 和 $push

mongoose findOne and $push

我正在尝试:

1).检查 bookId 是否存在(此 bookId 用于存储在图书模块中的 google 本书 api)。

2).如果这本书不在数据库中,则保存它。

3).将 id (mongoose.Types.ObjectId) 添加到 'books' 字段数组中的用户(模块)。

目前我正在用静态测试测试“推送”,看起来它根本没有执行“推送”。我是初学者,所以非常感谢任何帮助。

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);
    });
});

Book.create 是异步的,您应该等待它。你可以做到

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

将图书推送到用户图书数组的 .then 应该链接到 Book.create