mongoose model.create() is not allowing duplicate inputs without any key in model being `’unique:’true’`

I am using mongoose along with nodejs to insert data. I am using MVC and in my controller I have this code:

module.exports.create_tracsaction = function (req, res) {
    Company.findOne({ username: req.body.req_from }, function (err, user) {
        if (user.vaccine.extra < req.body.req_vac) {
            return res.redirect('/vaccine');
        }
        else {
            var data = {
                req_from: req.body.req_from,
                req_to: req.body.req_to,
                amt_req: req.body.req_vac,
                transaction_status: "Awaiting confirmation",
                vaccine: user.vaccine.name,
                transaction_value: user.vaccine.price * req.body.req_vac
            }
            Transaction.create(data);
            return res.redirect('/vaccine');
        }
    })
    console.log(req.body);
};

This is my schema

const transactionSchema = new mongoose.Schema({
    req_from: {
        type: String,
        required: true
    },
    req_to: {
        type: String,
        required: true
    },
    amt_req: {
        type: Number,
        required:true
    },
    transaction_status: {
        type: String,
        default: "Awaiting confirmation"
    },
    vaccine: String,
    transaction_value: Number
}, {
    timestamps: true
});

Even though non of the fields have property unique:'true', I am getting this error:

MongoError: E11000 duplicate key error collection: innovate_dev.transactions index: username_1 dup key: { username: null }

How to remove this error? The first time I sent data from views there was no error but from thereafter it’s giving this error every time.

Let me know if you need anything else. Thanks in advance ๐Ÿ˜€

Answer

It looks like a unique index got created at some point on the username field of transactions. That according your schema, it no longer exists. Thus every time you make an entry null is being indexed and throwing an error.

If you are using Compass or another GUI you can go in and delete it.

Otherwise to remove with MongoShell:

use innovate_dev

It will switch to your db

db.transactions.dropIndex('username_1')

Leave a Reply

Your email address will not be published. Required fields are marked *