node.js - "ERROR:MongoServerError: E11000 duplicate key error collection: myFirstDatabase.files index: key_1 dup key: { key: null }"

标签 node.js mongodb mongoose

我正在尝试在我的 api 中集成创建用户的可能性。我正在使用 Node 和 mongodb。这是我的架构:

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

const FileSchema = new Schema({
    name: {
        type: String,
        required: true,
        minlength:1,
        unique:false,
    }, extension: {
        type:String,
        required:true,
        unique:false,
    }, content: {
        type:String,
        required:true,
        unique:false,
    },group:{
        type:String,
        required:false,
        unique:false,
    }, creator:{
        type: String,
        required: true,
        unique:false,
    }
})

const File = mongoose.model('File', FileSchema);

module.exports = File;

这是我的功能:

const createNewFile = (req, res) => {
    const name = req.body.name;
    const extension = req.body.extension;
    const creator = req.body.creator;
    const group = req.body.group;
    console.log(req.body)

    const newFile = new File({name, extension, content:'Write your code here',creator, group:group});

    newFile.save()
        .then(() => res.json('200'))
        .catch(err => res.status(400).json('ERROR:'+err))
}

Insomia 和 Postman 控制台返回标题中的错误。我该怎么做才能避免这个错误?我添加了 unique: false 因为我在另一个问题中读到了它,但它还是失败了。有人可以帮帮我吗?当数据库为空时,我可以创建第一个元素。然后,当我创建第二个时,错误出现。请帮助我

最佳答案

在 mongodb Node 中有一个唯一索引 {key: 1}files集合myFirstDatabase数据库。

我怀疑这是在您测试潜在架构设计时创建的。

为了插入不包含该字段唯一值的文档(包括不包含该字段),需要删除该索引。

实现这一目标的几种方法:

  • 使用 mongo shell 或 Compass 或 Robo3t 等管理工具连接到 mongod,并手动删除索引
  • 使用syncIndexes由 Mongoose 提供
  • 删除 files收藏
  • 删除 myFirstDatabase数据库
  • 停止 mongod,删除整个 dbpath,然后使用干净的实例重新开始

关于node.js - "ERROR:MongoServerError: E11000 duplicate key error collection: myFirstDatabase.files index: key_1 dup key: { key: null }",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70187780/

相关文章:

node.js - 将外部 javascript 和 css 文件链接到 Vue 组件中?

node.js - 如何在 mongodb 中为深度嵌套数组编写更新查询?

node.js - Mongoose:在设置值后,为新创建的对象的值转换为 ObjectId 失败

mongodb - 如何使用 mongoose 将文档插入 mongodb 并获取生成的 id?

javascript - grunt.task.run 上带有变量的 Grunt for 循环

javascript - 如何使用 Express 从一个端点发送多个查询?

javascript - 高级字符串本地化

ruby-on-rails - Rails 有两个不同的数据库

node.js - 通过 mongodb 保存表单部分

javascript - Mongoose 不发送更新结果