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 ?