嵌套函数不执行NodeJS,Mongoose

时间:2018-01-27 11:01:28

标签: javascript node.js mongoose

我创建了一个函数,正在查找匹配_id的任何预留文档,如果存在被删除,接下来执行Book(findById)函数,该函数正在查找使用函数的任何书籍(findOneAndUpdate),如果存在则添加数值+ 1.但我不知道为什么,但功能不想完成。

router.post('/cancel-reservation', (req, res) => {
  var reservation = req.body.reservation;

  Reservation.findByIdAndRemove(reservation._id, function (err) {
    if (err) throw err;
    else {


      Book.findById(reservation.idBook, (err, book) => {
        if (err) throw err;
        if (book == null) {

         //////////// //*WORKING *////////////////

          let bookObj = {
            name: reservation.nameBook,
            description: reservation.description,
            publishingHouse: reservation.publishingHouse,
            quantity: 1,
            year: reservation.year,
            sites: reservation.sites
          };

          var book = new Book(bookObj);

          book.save()
            .then(function (book) {
              res.json(book)
            })
            .catch((err) => {
              res.json('not saved')
            })


         //////////// //*WORKING *////////////////


        } else if (book) {

          // findOneAndUpdate
         //////////// //*HERE IS PROBLEM *////////////////

          book.quantity = book.quantity+1; 

          console.log(book._id)

          Book.findOneAndUpdate({ _id: book._id },
            { $set: { quantity : book.quantity } }, { upsert: true }),
            ((err, complete) => {
              if(err) console.log('errrrrr');
              else {
                console.log(complete)
                console.log('complete')
                  res.json(complete)

              }
            })
        }
      });
    }
  });
});

这个问题可能与findOneAndUpdate函数嵌套在findById中有关吗?

1 个答案:

答案 0 :(得分:0)

我认为findOneAndUpdate

上有一个额外的括号
Book.findOneAndUpdate({ _id: book._id },
       { $set: { quantity : book.quantity } }, { upsert: true },
       (err, complete) => {
         if(err) console.log('errrrrr');
         else {
           console.log(complete)
           console.log('complete')
             res.json(complete)

         }
       })