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.
CodePudding user response:
.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