【问题标题】:Mongoose findOneAndUpdate not updating猫鼬 findOneAndUpdate 不更新
【发布时间】:2020-11-13 21:54:31
【问题描述】:

我正在尝试在单击按钮时将布尔值更新为 true。当我在控制器更新方法中 console.log 响应的正文时,更新的字段是正确的,但在数据库中没有更改。响应也很大,所以我认为我发送的内容有问题。我设置了 {new: true} ,但仍然没有区别。我在这里做错了什么。这是我的代码:

型号

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;

反应

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

API

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

路由

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

猫鼬控制器

  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));
  },

【问题讨论】:

  • 更新后必须保存文档。
  • @butthash3030 您可以使用updateOne() 方法,而不是使用findOneAndUpdate() 然后保存文档。此外,这个问题看起来与此类似,stackoverflow.com/questions/51160223/…
  • @KarthickRam 我选择了您的解决方案,并且效果很好。谢谢!

标签: node.js reactjs express mongoose


【解决方案1】:

更新后必须保存文档

 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));
  }

【讨论】:

    猜你喜欢
    • 2013-02-13
    • 2022-01-22
    • 2021-09-25
    • 2017-10-05
    • 2018-07-10
    • 2015-09-15
    • 2016-06-20
    • 2018-07-15
    • 2013-06-19
    相关资源
    最近更新 更多