Home > Mobile >  How to convert Model.updateOne() to Model.findOne() first then Model.set() then Model.save()
How to convert Model.updateOne() to Model.findOne() first then Model.set() then Model.save()

Time:02-11

I have a mongodb People document like this:

[
 {
    _id: "1234567890",
    name: "El Wood",
    jobs: [
       {
          _id: "job1",
          title: "teacher"
       },
       {
          _id: "job2",
          title: "programmer"
       }

    ]
 },
 ...
]

I want to update (update one) job1 title from teacher to lecturer.

Im using express and mongoose.

My first method is:

await People.updateOne({ "jobs._id": "job1" }, { $set: { "jobs.$.title": "lecturer" } });

And code above is work.

My second method is findOne() first, than set(), than save():

const peopleToUpdate = await People.findOne({ "jobs._id": "job1" }) // 
peopleToUpdate.set({ "jobs.$.title": "lecturer" })
peopleToUpdate.save()

but the second method its doesn't work, the job1 title is not changing.

how to update the job1 title using second method way?

CodePudding user response:

That's happened because you're using asynchronous. To able use the second method you need to use promises

const peopleToUpdate = await People.findOne({ 'jobs._id': 'job1' })
    .then(function (doc) {
        doc.title = 'lecturer';
        return doc.save();
    })
    .then(console.log)
    .catch(function (err) {
        handleError(err);
    });

Please read these docs as your references

https://mongoosejs.com/docs/async-await.html#basic-use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

  • Related