简体   繁体   中英

.save is not a function in Mongoose

What is wrong with the way I am using Mongo? I am simply trying to update a record.

Here is my code:

async function updateReview (req, res) {
  const review = {
    ...req.body
  }

  const existingReview = await Review.findOne({
    userId: review.userId,
    launchId: review.launchId
  }).lean() 

  if (!existingReview) {
    return res.status(404).send()
  }
  existingReview.content = review.content
  existingReview.displayName = review.displayName
  existingReview.rating = review.rating

  await existingReview.save()
  return res.status(200)
}

So all I want to do is find the existing review and update some fields and save it. My code fails on the line: await existingReview.save() . The error says that .save is not a function.

.save() function doesn't exist because you called .lean() which returns a normal JS object instead of a Mongoose object.

Instead of using .save() use one of the following options:

Example 1

async function updateReview (req, res) {
  const review = {
    ...req.body
  }

  const existingReview = await Review.findOne({
    userId: review.userId,
    launchId: review.launchId
  }).lean() 

  if (!existingReview) {
    return res.status(404).send()
  }

  const { content, displayName, rating } = review;
  const { _id } = existingReview;

  await Review.updateOne({ _id }, { content, displayName, rating });

  return res.status(200)
}

Example 2

async function updateReview (req, res) {
  const review = {
    ...req.body
  }

  const existingReview = await Review.findOne({
    userId: review.userId,
    launchId: review.launchId
  }).lean() 

  if (!existingReview) {
    return res.status(404).send()
  }

  const { content, displayName, rating } = review;
  const { _id } = existingReview;

  await Review.findOneAndUpdate({ _id }, { content, displayName, rating }).lean();

  return res.status(200)
}

Since you don't need the updated object, use updateOne instead of findOneAndUpdate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM