本文介绍了Mongoose - 版本错误:没有找到与 id 匹配的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Context:我有一个 Post Mongoose 模型,它包含一个 csv_files 数组字段来存储 csv 字符串.我从不同的 Web 应用程序发出 fetch API 请求,以 POST 特定 Post 的 csv 字符串.

Context: I have a Post Mongoose model that contains a csv_files array field to store csv strings. I make a fetch API request from a different web app to POST the csv strings for a particular Post.

下面的代码产生错误

UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 ID:2):版本错误:未找到 ID 为5966932399e969ad8013bedf"的匹配文档

router.js

router.post('/posts/:url/upload-csv/:csv_name', (req, res) => {
  let csv_name = req.params.csv_name;
  let csv_string = csv_name+req.body.csv_string;

  Post.findOne({url: req.params.url})
    .then((post) => {
      if (post.csv_files.length === 0) {
        post.csv_files.push(csv_string);
      } else {
        let foundExistingCSV = false;
        for (var i = 0; i < post.csv_files.length; i++) {
          if (post.csv_files[i].includes(csv_name)) {
            foundExistingCSV = true;
            post.csv_files[i] = csv_string;
            break;
          }
        }
        if (!foundExistingCSV) post.csv_files.push(csv_string);
      }

      post.markModified('csv_files');
      post.save();

      return res.status(200);
    })
    .catch((err) => {
      console.log(err);
      return res.status(400);
    });
});

模型/post.js

const mongoose    = require('mongoose');

var stringPreset = {
  type: String,
  uppercase: true
}

var Post = mongoose.model('Post', {
  name                 : stringPreset,
  url                  : String,
  password             : String,
  csv_files            : { type : Array , "default" : [] },
  updatedAt            : { type: Date, default: Date.now }
});

module.exports = { Post };

如何解决这个问题,以便文档保存到 csv_files 数组中而不会出错?

How can I fix this so that the document saves into the csv_files array without the error?

推荐答案

在将对象保存到 Mongo DB 时,您必须了解 Mongo DB 具有适当的版本控制系统.这有助于确保您保存一次对象后,再次保存时不会覆盖之前保存的数据.

When saving an object to Mongo DB you have to understand that Mongo DB has a version control system in place. This helps ensure that if you save an object once, when saving it again you don't end up overwriting the previously saved data.

这是您看到的错误.如果您想在此特定实例中不考虑版本控制而强制更新对象,您可能需要使用 .update() 代替.这将强制更新对象,而不管其当前保存的状态如何.

This is the error you're seeing. If you want to force the object to update regardless of version control in this particular instance you may want to use .update() instead. This will force the object to be updated regardless of its currently saved state.

这是因为.save()关注并关注版本控制,而.update()会更新对象而不管版本控制.

This is because .save() watches and cares about version controls, while .update() will update the object regardless of version control.

这篇关于Mongoose - 版本错误:没有找到与 id 匹配的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 22:21