user13023516
user13023516

Reputation:

Update a document and return the updated document

const _id = req.params.id;
let tire = await TireModel.findOne({ _id });
tire = await tire.update({description : "new description"});
console.log(tire);

When I run this piece of code, I want the tire to be the updated one, but instead it returns the result of the operation in the database. I already tried the {new: true} option.

Upvotes: 0

Views: 67

Answers (2)

SuleymanSah
SuleymanSah

Reputation: 17898

After you find your document with findOne, you can update it's fields, and then use save() method:

const _id = req.params.id;
let tire = await TireModel.findOne({ _id });

if (tire) {
  tire.description = "new description";
  tire = await tire.save();
  console.log(tire);
} else {
  //todo
}

Upvotes: 2

blokberg
blokberg

Reputation: 994

You can use findOneAndUpdate() function.

const filter = { name: 'Jean-Luc Picard' };
const update = { age: 59 };

// `doc` is the document _after_ `update` was applied because of
// `new: true`
let doc = await Character.findOneAndUpdate(filter, update, {
  new: true
});
doc.name; // 'Jean-Luc Picard'
doc.age; // 59

More information https://mongoosejs.com/docs/tutorials/findoneandupdate.html

Upvotes: 2

Related Questions