首页 > 解决方案 > 不能向 MongoDB 集合添加超过 1 个对象

问题描述

伙计们,我正在构建我的 NodeJS API,为此我将通过 mongoose 模块使用 MongoDB。

我创建了架构、控制器和所有端点都可以工作,但我只能创建第一个 POST。我的意思是,我可以在 MongoDB 的集合中创建 1 个对象,创建之后,如果我尝试向数据库中添加任何其他内容,我会得到一个 MongoError,我不知道该做什么,也没有找到互联网上的任何东西..

我希望你能帮助我...

这是架构:

const mongoose = require('mongoose');

const ProjectSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        unique: true
    },
    description: {
        type: String,
        required: true
    },
    app: {
        type: String,
        required: false,
    },
    github: {
        type: String,
        required: false,
    },
    logo: {
        type: String,
        required: false
    }
});

const Project = mongoose.model('project', ProjectSchema);

module.exports = Project;

控制器:

const Project = require("../models/ProjectSchema");

class ProjectController {
    async addNewProject(req, res) {
        try {
            const data = await Project.create(req.body);
            return res.send(data);
        } catch(error) {
            return res.send(error);
        }
    }
    
    async listAllProjects(req, res) {
        try {
            const data = await Project.find({});

            return res.send(data);
        } catch(error) {
            return res.send(error);
        }
    }
}

module.exports = new ProjectController();

POST 请求 JSON:

{
    "name": "name",
    "description": "description",
    "app": "app",
    "github": "github",
    "logo": "logo"
}

当数据添加到数据库时,我的 API 的预期响应是数据本身,如下所示:

{
  "_id": "603ac9d621540e1748b5d21f",
  "name": "name",
  "description": "description",
  "app": "app",
  "github": "github",
  "logo": "logo",
  "__v": 0
}

在第一个 POST 请求中,它确实发生了。但在那之后,这就是我得到的:

{
  "driver": true,
  "name": "MongoError",
  "index": 0,
  "code": 11000,
  "keyPattern": {
    "id": 1
  },
  "keyValue": {
    "id": null
  }
}

PS.:我已经尝试过使用旧版本的猫鼬,但我得到了同样的东西......就像猫鼬 5.11.15、5.11.17 和目前最新的 5.11.18。

提前致谢!

编辑。:

没有捕获的错误:

(node:1500) UnhandledPromiseRejectionWarning: MongoError: E11000 duplicate key error collection: GithubProjects.projects index: id_1 dup key: { id: null }
    at Function.create (C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\core\error.js:57:12)
    at toError (C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\utils.js:123:22)
    at C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\operations\common_functions.js:258:39
    at handler (C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\core\sdam\topology.js:943:24)
    at C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\cmap\connection_pool.js:350:13
    at handleOperationResult (C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\core\sdam\server.js:558:5)
    at MessageStream.messageHandler (C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\cmap\connection.js:277:5)
    at MessageStream.emit (events.js:315:20)
    at processIncomingData (C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\cmap\message_stream.js:144:12)
    at MessageStream._write (C:\Users\joaov\Desktop\ms-sapi-getRepos\node_modules\mongodb\lib\cmap\message_stream.js:42:5)
    at writeOrBuffer (internal/streams/writable.js:358:12)
    at MessageStream.Writable.write (internal/streams/writable.js:303:10)
    at TLSSocket.ondata (internal/streams/readable.js:719:22)
    at TLSSocket.emit (events.js:315:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
(node:1500) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1500) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```

标签: node.jsjsonmongodbmongoose

解决方案


删除唯一索引“id_1”,例如从 mongo shell:

db.projects.dropIndex("id_1")

您的架构中没有“id”字段,因此 mongoose 插入没有“id”的文档。Mongo 默认为“null”,它适用于第一个文档。当您插入第二个时,它违反了唯一约束。

我猜你是不小心创建了索引,删除它是安全的。否则,您需要更改架构和应用程序逻辑以向 id 字段提供唯一值。


推荐阅读