This happens because you're saving the duplicated document before mongoose
has finished creating the index. Mongoose creates the indexes on the go, after your app has started.
So, to ensure that your document will be saved only after the indexes were created, you have to listen to the index
event of your model. For example:
Model.on('index', function (error) {
console.log(jp);
jp.save(function(err){
console.log(err);
var jp2 = new Model({ phone: "123456"});
console.log(jp2);
jp2.save(function(err){
console.log(err);
process.exit();
});
})
});
Now, when you try to save the second document (the duplicated one), your MongoDB will raise an error, because your save
calls will just run after the indexes were created.