João Casarin
João Casarin

Reputation: 926

Can't add more than 1 object to MongoDB collection

Well guys, I'm building my NodeJS API, and for that I'll be using MongoDB through mongoose module.

I created my Schema, controllers, and all my endpoints do work, but I'm able to create only the first POST. I mean, I can create 1 object in the collection of MongoDB, after that creation, if I try to add anything else to the database, I get a MongoError, I can't find out what to do, and also haven't found anything on internet..

I hope you can help me with that...

This is the Schema:

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;

Controller:

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 request JSON:

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

The expected response from my API, when the data is added to the database, is the data itself, like this: RESPONSE:

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

And on the first POST request, it does happen. But after that, this is what I get:

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

PS.: I have already tried with older versions of mongoose, but I got the same thing... Like mongoose 5.11.15, 5.11.17, and currently on latest 5.11.18.

Thanks in advance!

edit.:

Error without catching:

(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.```

Upvotes: 0

Views: 880

Answers (1)

Alex Blex
Alex Blex

Reputation: 37048

Delete unique index "id_1", e.g. from mongo shell:

db.projects.dropIndex("id_1")

You don't have "id" field in your schema so mongoose inserts the document without "id". Mongo defaults it to "null" and it works for the first document. When you insert the second one it violates unique constraint.

I guess you created the index by accident and it's safe to remove it. Otherwise you need to change the schema and application logic to provide unique values to the id field.

Upvotes: 2

Related Questions