【问题标题】:NodeJS MongoDB Mongoose - Getting _.id of newly created SchemaNodeJS MongoDB Mongoose - 获取新创建的模式的 _.id
【发布时间】:2019-11-20 05:22:53
【问题描述】:

我有一个允许用户为图书评分的应用。这些书籍是从 Google Books API 调用的。当用户提交评分时,我只在我的数据库中保存这本书的副本。

reviews.put("/:id/new", async (req, res) => {
  let url = await `https://www.googleapis.com/books/v1/volumes/${req.params.id}`;
  console.log(url);
  await request(url, { json: true }, async (error, response, data) => {
    let newRating;
    Book.findOne({ id: req.params.id }, (err, result) => {
      if (err) console.log(err.message);
      if (result) {
        if (req.body.stars !== undefined) {
          newRating = /* some math formula */
        } else {
          newRating = /* some math formula */
        }
      } else {
        newRating = req.body.stars;
      }
    });
    Book.findOneAndUpdate(
      {
        id: req.params.id
      },
      {
        id: data.id,
        id: data.id,
        title: data.volumeInfo.title,
        description: data.volumeInfo.description,
        img: data.volumeInfo.imageLinks.thumbnail,
        author: data.volumeInfo.authors,
        rating: newRating,
        $inc: {
          ratingCount: 1
        }
      },
      {
        upsert: true,
        returnNewDocument: true
      },
      (err, book) => {
        console.log(book) // If its creating a new document, book returns null. If the book is already in the DB, book returns the document. 
        Review.create({
          rating: req.body.stars,
          review: req.body.review,
          reviewer: req.session.currentUser._id,
          book: book._id // <-- ERROR, cannot read property "_.id" of null
        });
      }
    );
  });

  res.redirect("/");
});

问题是book 在新创建时返回null。但是,如果其他人已经对其进行了评价,则此方法可以正常工作。我试过使用.save(),但没有奏效。不然怎么获得新书的_.id

感谢任何帮助。谢谢!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您正在通过不正确的query options。您需要使用:

    new: bool - 如果为真,则返回修改后的文档而不是原始文档。

    upsert: bool - 如果对象不存在则创建它。默认为 false。

    更新方法如下:

    Book.findOneAndUpdate(
          {
            id: req.params.id
          },
          {
            id: data.id,
            id: data.id,
            title: data.volumeInfo.title,
            description: data.volumeInfo.description,
            img: data.volumeInfo.imageLinks.thumbnail,
            author: data.volumeInfo.authors,
            rating: newRating,
            $inc: {
              ratingCount: 1
            }
          },
          {
            upsert: true,
            new: true
          },
          (err, book) => {
            console.log(book) // If its creating a new document, book returns null. If the book is already in the DB, book returns the document. 
            Review.create({
              rating: req.body.stars,
              review: req.body.review,
              reviewer: req.session.currentUser._id,
              book: book.id // <-- ERROR, cannot read property "_.id" of null
            });
          }
    

    docs

    【讨论】:

      【解决方案2】:

      像这样使用'new': true{ upsert: true, 'new': true }

      这应该返回插入的文档。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-30
        • 2016-09-12
        • 2018-06-07
        • 2020-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多