Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

.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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

.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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading