简体   繁体   English

"唯一验证在 Mongoose 中不起作用"

[英]Unique validation not working in Mongoose

I recognized this question has been<\/a> asked<\/a> before<\/a> , but none of the solutions seemed to work for me.我认识到这个问题以前曾被<\/a>问<\/a>过<\/a>,但似乎没有一个解决方案对我有用。

I have a simple model I'm defining like this:我有一个像这样定义的简单模型:

const mongoose = require('mongoose')
const { Schema } = mongoose

let subscriberSchema = new Schema({
  firstName: { type: String, required: true },
  email: { type: String, required: true, unique: true }
}, { timestamps: true })

let Subscriber = mongoose.model('Subscriber', subscriberSchema)

This is very complicated thing to solve with node, as you know its async.用 node 解决这个问题非常复杂,因为你知道它是异步的。 If you are running both queries parallel, both will check if doc exists as same time and both will try to create the record.如果您并行运行两个查询,则两者都会检查 doc 是否同时存在,并且两者都将尝试创建记录。

There are two things you could do.你可以做两件事。

Create Unique Index创建唯一索引

YourModel.index({ email: 1}, { unique: true })

OR或者
Use Update with $setOnInsert使用 $setOnInsert 更新

var pk = {email : 'your email'};
YourModel.update(pk, {
        $setOnInsert : data
    }, {upsert : true})

And Make sure the index exists in mongoDB.并确保索引存在于 mongoDB 中。

Mongoose does not modify index on key set. Mongoose 不会修改键集上的索引。 First try to remove index from mongo shell.首先尝试从 mongo shell 中删除索引。

 db.collection.dropIndex({email : 1})

Restart node process and mongoose will now create index with unique constraint.重新启动节点进程,猫鼬现在将创建具有唯一约束的索引。

Actually, unique option for validation working,how?Follow these steps:实际上,验证工作的独特选项,如何?请按照以下步骤操作:
1)set unique: true for certain field in schema(example "email") 1)设置唯一:对于架构中的某些字段(例如“电子邮件”)为真
2)drop whole db 2)删除整个数据库
3)restart node server 3)重启节点服务器
4)test in postman and you will see than now works 4)在邮递员中测试,你会看到比现在更有效

Cheers.干杯。

Make autoIndex: true while connecting to the database.连接到数据库时使 autoIndex: true 。

mongoose
.connect('connection url', {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    autoIndex: true, //make this true
})
.then(() => {
    console.log('Connected to mongoDB');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM