猫鼬唯一验证不起作用.重复的条目被保存 [英] Mongoose unique validation not working. Duplicate entries getting saved

查看:43
本文介绍了猫鼬唯一验证不起作用.重复的条目被保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a NodeJS application where, express is the framework & MongoDB is the database. I am using mongoose plugin for it.

我有一个父模型.我已经在字段"移动"中添加了唯一性:true .但是,每当我添加相同的手机号码时,唯一性验证就会失败.什么也没有发生,而是保存了重复的文档.所需的验证工作正常,但唯一验证仅在此特定模型中不起作用.

I have a parent model. I have added unique: true to field "mobile". But whenever I add same mobile number, uniqueness validation fails. Nothing happens rather duplicate document gets saved. The required validation works fine but unique validation does not work only in this particular model.

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

推荐答案

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

Use the following code to check if mongoose could able to create index:


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端创建索引.

If it gives error, you can create index on MongoDB side.

db.parents.createIndex( { "mobile": 1 }, { unique: true } );

文档中说:

在生产环境中,您应该使用 MongoDB外壳程序,而不是依靠猫鼬为您完成.这 模式的唯一选项便于开发和 文档,但猫鼬不是索引管理解决方案.

In a production environment, you should create your indexes using the MongoDB shell rather than relying on mongoose to do it for you. The unique option for schemas is convenient for development and documentation, but mongoose is not an index management solution.

这篇关于猫鼬唯一验证不起作用.重复的条目被保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆