Node.js Mongoose唯一验证不起作用。正在保存重复的条目

Node.js Mongoose唯一验证不起作用。正在保存重复的条目,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在开发一个NodeJS应用程序,其中express是框架,MongoDB是数据库。我正在使用mongoose插件 我有一个家长模型。我已经在字段“mobile”中添加了unique:true。但每当我添加相同的手机号码时,唯一性验证就会失败。如果保存重复的文档,则不会发生任何事情。所需的验证工作正常,但唯一的验证不仅在这个特定模型中有效 下面是模型 parentModel.js var mongoose = require('mongoose'); var bcrypt = require(

我正在开发一个NodeJS应用程序,其中express是框架,MongoDB是数据库。我正在使用mongoose插件

我有一个家长模型。我已经在字段“mobile”中添加了unique:true。但每当我添加相同的手机号码时,唯一性验证就会失败。如果保存重复的文档,则不会发生任何事情。所需的验证工作正常,但唯一的验证不仅在这个特定模型中有效

下面是模型 parentModel.js

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
mongoose.set('useCreateIndex', true);
var Schema   = mongoose.Schema;

var parentSchema = new Schema({
    'name' : {
    type: String,
    required: true
  },
    'mobile' : {
    type: Number,
    unique: true,
    required: true
  },
    'password' : {
    type: String,
    select: false
  },
    'address' : {
    type: String,
    required: true
  },
    'notifications' : [{
        'title': {
        type: String,
        required: true
      },
      'body': {
        type: String,
        required: true
      },
      'path': {
        type: String,
        required: true
      },
    }],
    'activities' : [{
        'title': {
        type: String,
        required: true
      },
      'body': {
        type: String,
        required: true
      },
      'date': {
        type: Date,
        required: true
      }
    }],
    'isVerified' : {
        type: Boolean,
    default: false
    }
},
{
    timestamps: true
});

parentSchema.pre('save', function (next) {
  var parent = this;
  if (this.isNew) {
    var randomstring = Math.random().toString(36).slice(-8);
    bcrypt.genSalt(10, function (err, salt) {
      if (err) {
        return next(err);
      }
      bcrypt.hash(randomstring, salt, null, function (err, hash) {
        if (err) {
          return next(err);
        }
        parent.password = hash;
        next();
      });
    });
  } 
  else if (this.isModified('password')) {
    bcrypt.genSalt(10, function (err, salt) {
      if (err) {
        return next(err);
      }
      bcrypt.hash(parent.password, salt, null, function (err, hash) {
        if (err) {
          return next(err);
        }
        parent.password = hash;
        next();
      });
    });
  }
  else {
    return next();
  }
});

parentSchema.methods.comparePassword = function (passw, cb) {
  console.log(passw)
    bcrypt.compare(passw, this.password, function (err, isMatch) {
        if (err) {
            return cb(err);
        }
        cb(null, isMatch);
    });
};

module.exports = mongoose.model('parent', parentSchema);
create: function (req, res) {
        var parent = new parentModel({
            name : req.body.name,
            mobile : req.body.mobile,
            address : req.body.address

        });

        parent.save(function (err, parent) {
            if (err) {
                return res.status(500).json({
                    message: 'Error when creating parent',
                    error: err
                });
            }
            return res.status(201).json(parent);
        });
    }
下面是控制器 parentController.js

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
mongoose.set('useCreateIndex', true);
var Schema   = mongoose.Schema;

var parentSchema = new Schema({
    'name' : {
    type: String,
    required: true
  },
    'mobile' : {
    type: Number,
    unique: true,
    required: true
  },
    'password' : {
    type: String,
    select: false
  },
    'address' : {
    type: String,
    required: true
  },
    'notifications' : [{
        'title': {
        type: String,
        required: true
      },
      'body': {
        type: String,
        required: true
      },
      'path': {
        type: String,
        required: true
      },
    }],
    'activities' : [{
        'title': {
        type: String,
        required: true
      },
      'body': {
        type: String,
        required: true
      },
      'date': {
        type: Date,
        required: true
      }
    }],
    'isVerified' : {
        type: Boolean,
    default: false
    }
},
{
    timestamps: true
});

parentSchema.pre('save', function (next) {
  var parent = this;
  if (this.isNew) {
    var randomstring = Math.random().toString(36).slice(-8);
    bcrypt.genSalt(10, function (err, salt) {
      if (err) {
        return next(err);
      }
      bcrypt.hash(randomstring, salt, null, function (err, hash) {
        if (err) {
          return next(err);
        }
        parent.password = hash;
        next();
      });
    });
  } 
  else if (this.isModified('password')) {
    bcrypt.genSalt(10, function (err, salt) {
      if (err) {
        return next(err);
      }
      bcrypt.hash(parent.password, salt, null, function (err, hash) {
        if (err) {
          return next(err);
        }
        parent.password = hash;
        next();
      });
    });
  }
  else {
    return next();
  }
});

parentSchema.methods.comparePassword = function (passw, cb) {
  console.log(passw)
    bcrypt.compare(passw, this.password, function (err, isMatch) {
        if (err) {
            return cb(err);
        }
        cb(null, isMatch);
    });
};

module.exports = mongoose.model('parent', parentSchema);
create: function (req, res) {
        var parent = new parentModel({
            name : req.body.name,
            mobile : req.body.mobile,
            address : req.body.address

        });

        parent.save(function (err, parent) {
            if (err) {
                return res.status(500).json({
                    message: 'Error when creating parent',
                    error: err
                });
            }
            return res.status(201).json(parent);
        });
    }

使用以下代码检查mongoose是否能够创建索引:


const Parent = mongoose.model('parent', parentSchema);

Parent.on('index', function(err) { 

  if (err) {
    console.log("Could not create index: ", err)
  } else {
    console.log("Index created")
  }

});

module.exports = Parent;
如果出现错误,您可以在MongoDB端创建索引

db.parents.createIndex( { "mobile": 1 }, { unique: true } );
在报告中说:

在生产环境中,应该使用 MongoDB外壳,而不是依靠mongoose为您做这件事。这个 模式的唯一选项便于开发和维护 文档,但mongoose不是索引管理解决方案


这回答了你的问题吗?不,我试过使用index:true。什么也没发生。所需的验证工作正常,但唯一的验证在这个特定的模型中不起作用。非常感谢。该索引不存在。我还有一个问题,如果我们一起使用index:true和unique:true呢?当我添加index:true并删除集合时,我当前的问题就解决了。我将使用db.parents.createIndex({“mobile”:1},{unique:true});或者index:true?@BibekDas我猜是这样的
db.parents.createIndex({“mobile”:1},{unique:true})
,在mongodb的官方文档中,他们是这样使用的。当然我可能错了。但可能是将index:true添加到模型的键中,这正是mongoose做这件事的方法,db.parents.createIndex({“mobile”:1},{unique:true})。不过我不确定。无论如何,非常感谢你的帮助。非常感谢。