Search code examples
angularjsmongooseangularjs-directivemongoose-schemamongoose-populate

Mongoose: How to avoid inserting duplicate records?


I have written the following mongoose function to create new document in mongodb

createdata: (body) => {
    let sEntry = new SData(Object.assign({}, {
        dataId: body.DataId
    }));
    return sEntry.save();
}

I want to modify the above logic so that it doesn't insert two rows with same dataId

In other words, if a particular value of dataId is already existing in mongo then it should not create another entry with same dataId


Solution

  • You need to first install this mongoose-unique-validator for that. Then after you can define unique: true in

    In the second step, you need to define the unique: true in your schema. and also you have to handle the error response.

    var SData = mongoose.Schema({
        dataId: { type: String, index: true, unique: true, required: true },
    });
    
    createdata: (body) => {
        let sEntry = new SData(Object.assign({}, {
            dataId: body.DataId
        }));
        return sEntry.save(function() {
            console.log(error)
        });
    }