butthash3030
butthash3030

Reputation: 173

Mongoose findOneAndUpdate not updating

I am trying to update a boolean value to true on a button click. When I console.log the body of the response in the controller update method, the updated field is correct, but it is not changed in the database. Also the response is gigantic, so I'm thinking that something is wrong in what I am sending. I have {new: true} set, but still no difference. I'm doing something wrong here. Here is my code:

Model

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const albumSchema = new Schema({
    albumId: { type: String },
    title: { type: String },
    artist: { type: String },
    tracks: { type: [String], required: true },
    year: { type: Number, required: true },
    thumbnail: { type: String },
    description: { type: String },
    listened: { type: Boolean, default: false },
});

const Album = mongoose.model("Album", albumSchema);

module.exports = Album;

React

    changeStatus = (album) => {
      album.listened = true;
      API.updateAlbum(album)
    }

API

  updateAlbum: function(album) {
    return axios.put(`/api/albums/${album._id}`, album);
  },

Routing

router.route("/albums/:id").put(albumController.update)

Mongoose Controller

  update: function(req, res) {
    db.Album.findOneAndUpdate({ id: req.params.id }, req.body, { new: true })
      .then(dbAlbum => res.json(dbAlbum.body))
      .catch(err => res.status(422).json(err));
  },

Upvotes: 1

Views: 1467

Answers (1)

prax
prax

Reputation: 286

You have to save the document after updating it

 update: function(req, res) {
    db.Album.findOneAndUpdate({ id: req.params.id }, req.body, { new: true })
      .then((dbAlbum)=>{
          dbAlbum.save()
            .then((saved)=>{
                res.json(dbAlbum)
            })
            .catch((err)=>{
                res.status(422).json(err)
            })

      })
      .catch(err => res.status(422).json(err));
  }

Upvotes: 2

Related Questions