【问题标题】:Mongoose unique validation not working. Duplicate entries getting savedMongoose 唯一验证不起作用。重复条目被保存
【发布时间】:2020-04-13 14:01:59
【问题描述】:

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

我有一个父模型。我已将 unique: true 添加到“mobile”字段。但是每当我添加相同的手机号码时,唯一性验证都会失败。什么都没有发生,而是保存了重复的文档。所需的验证工作正常,但唯一验证不仅在此特定模型中有效。

下面是模型 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);

下面是控制器 parentController.js

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 Not Creating Indexes
  • 不,我尝试过使用 index: true。什么都没发生。所需的验证工作正常,但唯一验证在此特定模型中不起作用。

标签: node.js mongodb express mongoose


【解决方案1】:

使用以下代码检查 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 } );

docs 中写道:

在生产环境中,您应该使用 MongoDB shell 而不是依靠 mongoose 来为你做这件事。这 模式的独特选项便于开发和 文档,但 mongoose 不是索引管理解决方案。

【讨论】:

  • 非常感谢。该索引不存在。我还有一个问题,如果我们一起使用 index: true 和 unique: true 怎么办?一旦我添加了 index:true 并删除了集合,我当前的问题就解决了。我会使用 db.parents.createIndex( { "mobile": 1 }, { unique: true } );或索引:真?
  • @BibekDas 我猜是这样的 db.parents.createIndex( { "mobile": 1 }, { unique: true } ) ,在 mongodb 的官方文档中,他们是这样使用的。 docs.mongodb.com/manual/core/index-unique/…
  • 当然。我可能错了。但可能会在模型的键中添加 index: true 是做这件事的猫鼬方式,db.parents.createIndex( { "mobile": 1 }, { unique: true } )。不过不确定。无论如何,非常感谢您的帮助。非常感谢。
猜你喜欢
  • 2016-09-11
  • 2020-12-30
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多