0

I am trying to avoid duplicates from being saved in the system, and have implemented the model like so...

var mongoose = require('mongoose'),
    ObjectId = mongoose.Schema.Types.ObjectId,
    Schema = mongoose.Schema;

var User = require('../models/user.js');

var Stamp = new Schema({ 
    name: {type: String, unique: true },
    creatorId: {type: ObjectId, ref: 'User'},

    dateAdded: {type: Date}
}, {collection: "stamps"});

Stamp.index({name: 'text'});

//to avoid duplicate names
Stamp.path('name').index({ unique: true });

module.exports = mongoose.model('Stamp', Stamp);

The code for saving the new stamp:

var new_stamp = new Stamp ({
                    name: stampname,
                    creatorId: creatorId,
                    dateAdded: dateAdded
                });


                new_stamp.save(function(err, results){
                    if(!err) {
                        console.log('stamp has been added to the db');

            } else {
                console.log("Error creating stamp " + err);

            }
        });

How do I stop from duplicates being saved?

Tony Barnes
  • 2,625
  • 1
  • 18
  • 29
Lion789
  • 4,402
  • 12
  • 58
  • 96

0 Answers0