首页 > 解决方案 > Mongoose 为新数据返回重复键

问题描述

我的问题是我正在编写一个脚本以通过发布请求将 JSON 存储在数据库服务器上。有这样的问题:

首次在服务器重启时,每一个 JSON 都提交成功。之后,将不会提交任何 JSON 数据并给出 mongoose 重复 id 问题。

E11000 duplicate key error index: [database_name].[collection].$_id_ dup key: { : "2c73c49d-8ad2-49bf-b5a1-520aa595df17" }
new Schema({
  _id: { type: String, default: uuidv4() },
  ... // remainings
}
function (req, res) {
    models
     .create({'---': req.body.---, ..., ..., ..., ...})
     .then(result => res.json(result))
     .catch(err => {
       res.send(err.message);
     });
}

标签: node.jsexpressmongooseuuid

解决方案


default参数应该是一个函数

如果您传递uuidv4()它,它将在创建 Schema 时传递一个生成的值,并将该值用于所有文档。

架构应该这样定义。

new Schema({
  _id: { type: String, default: uuidv4 },
  ... // remainings
}

推荐阅读