0

Consider Schema Lead :

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const LeadsSchema = new Schema({
  supplier: {
    type: Schema.Types.ObjectId,
    ref: "suppliers",
    required: false
  },
  PhoneNumber: {
    type: String,
    required: true,
    unique: true
  },
  BusinessName: {
    type: String,
    required: true
  } ...
  ...
  ...
});

   module.exports = Lead = mongoose.model(
  "leads",
  LeadsSchema.index({ PhoneNumberMasque: 1 }, { expireAfterSeconds: 3600 })
);

And the action of inserting into Mongo :

   Leads.insertMany(leadsToInsert, { ordered: true })
            .then(function(docs) {
              console.log("Number of documents inserted: " + docs.length);
              return res
                .status(200)
                .json({ msg: "Documents uploaded to MongoDB Successfully!" });
            })
            .catch(function(err) {
              // error handling here
              console.log("Failed to insert Bulk..." + err.message);
              return res.status(500).json({ msg: err.message });
            });

The problem is that even though I set PhoneNumber as index and unique , Mongo keeps inserting all the documents regardless if there are duplicates or not.

Why ?

JAN
  • 21,236
  • 66
  • 181
  • 318
  • https://stackoverflow.com/a/47149286/3858638 – Shihab Oct 29 '19 at 09:51
  • 1
    If you can insert "duplicate data to a property" ( really lacking an example as proof within your question ) then there basically is **not** a "unique" index in force. All the `unique` property on a Mongoose Schema does is set's up the creation of a "unique index" with MongoDB on that property. Note *strongly*, that if your collection already contains data that *is not "unique"* on this property before you defined it in the schema, then the index **will not be created** and as such the "rule" cannot be enforced. – Neil Lunn Oct 29 '19 at 10:11
  • @NeilLunn: Actually I'm not creating the DB , I'm using the Schema to make my queries and when there is not collection , the Mongoose wrapper creates and collection.That's the problem maybe ? – JAN Oct 29 '19 at 10:18
  • 1
    Nope. Mongoose does not create a collection. You can read my comment and the linked answer for detail on what actually happens. Also [How does mongodb create database/collection on the fly](https://stackoverflow.com/q/28064159/2313887). Defining fields as `unique` or using the `.index()` method on a Mongoose Schema however is not something you can *undo*. If you change your mind, it's up to you to alter MongoDB directly. Also read the linked answer and the comment. **Duplicate data** is a **you** thing, and nothing to do with the application code. – Neil Lunn Oct 29 '19 at 10:32

0 Answers0