Categories
JavaScript Answers

How to find, modify, and save with Mongoose and JavaScript?

Spread the love

To find, modify, and save with Mongoose and JavaScript, we call findOne and save.

For instance, we write

User.findOne({ username: oldUsername }, (err, user) => {
  user.username = newUser.username;
  user.password = newUser.password;
  user.rights = newUser.rights;

  user.save((err) => {
    if (err) {
      console.error("ERROR!");
    }
  });
});

to call findOne to find the object with the username set to oldUsername.

In the callback, we set the property values for user.

And then we call user.save to save the values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *