yasmikash
yasmikash

Reputation: 157

Update a document returned by findOne()/find()/findById() - mongoose

I'm wondering that if there's any method available to change the values of available fields of a document object returned by mongoose find(),findOne() and findById() methods and update them with changes applied into the database. Below code snippet is what I'm expecting for to done the job I want:

User.findOne({ email: email })
      .then(user => {
        if (user) {
            user.fieldToUpdate = "Updated value"; // Here I'm getting the field and updating it with the new value;
            user.save().then().catch(); // Here I'm updating the document to the database, expecting for a promise object
        } else {
          const error = new Error("No such user in the database.");
          error.httpStatusCode = 422;
          next(error);
        }
      })
      .catch(error => {
        next(error);
      });

Upvotes: 0

Views: 310

Answers (1)

Arootin Aghazaryan
Arootin Aghazaryan

Reputation: 848

The code snippet you wrote will work fine, but if you need to just update the found document:

User.findOneAndUpdate({ email }, { email: '[email protected]' })
  .then((err, user) => {
    //
  }

More on the Docs

Upvotes: 1

Related Questions