node.js - 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);
});
}
解决方案
default
参数应该是一个函数
如果您传递uuidv4()
它,它将在创建 Schema 时传递一个生成的值,并将该值用于所有文档。
架构应该这样定义。
new Schema({
_id: { type: String, default: uuidv4 },
... // remainings
}
推荐阅读
- neo4j - Neo4j (3.5.14) 互连节点的 BFS/DFS 故障
- c - 你能确定 C 中的堆栈深度吗?
- visual-studio-code - vscode c/c++ 定义配置
- macos - 为什么逆向工程时,大小为 7.6 MB 的 APK 文件会在 exFAT 格式的外部硬盘驱动器上分配 1.36 GB?
- node.js - 使用虚拟 Alexa 设备进行持续集成?
- c# - 使用从 URL 提供的 LitJson 和 Json 文件代替本地 Json 文件
- c++ - 在 GitLab CI Docker 工作流程中应该在哪里编译 c++ 应用程序?
- c# - 带有 Aero Snap 的无边框表格在顶部创建白色边框
- javascript - 如何使用 JavaScript 从用户输入 (URL) 更改背景图像
- javascript - 在有或没有 jquery 的情况下使用延迟角承诺的正确方法是什么?