独特的验证在猫鼬中不起作用 [英] Unique validation not working in Mongoose

查看:42
本文介绍了独特的验证在猫鼬中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认识到这个问题已经asked 之前,但似乎没有一个解决方案适合我.

I recognized this question has been asked before, but none of the solutions seemed to work for me.

我定义了一个简单的模型:

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)

如果我运行以下命令(在 REPL 中,所以没有异步问题),我希望看到第二次调用 create 时记录的错误.

If I run the following (in the REPL, so no async issues), I'd expect to see an error being logged for the second call to create.

Subscriber.create({ firstName: "Landon", email: "example@example.com" })
Subscriber.create({ firstName: "Landon", email: "example@example.com" }, function(err) { 
  console.log("ERROR", err) 
})

相反,我看到了"ERROR" null.

如果我运行 count 查询或 find 查询,我可以看到两个模型都已创建.我做错了什么?

If I run a count query or a find query, I can see both models were created. What am I doing wrong?

编辑

以下是我已经尝试过的一些方法:

Here are a few of the things I've already tried:

  • 添加索引后重启MongoDB
  • 删除所有现有记录,以便没有可能违反唯一性约束的现有记录
  • 通过所有这些方式定义email 属性(我在不同的地方见过不同的实现):{ type: String, required: true, unique: true }, { type: String, required: true, index: true, unique: true }, { type: String, required: true, index: { unique: true } }.
  • Restart MongoDB after adding index
  • Removing all of the existing records so there are no existing records that could violate the uniqueness constraint
  • Defining the email attribute all of these ways (I've seen different implementations in different places): { type: String, required: true, unique: true }, { type: String, required: true, index: true, unique: true }, { type: String, required: true, index: { unique: true } }.

推荐答案

用 node 解决这个问题非常复杂,因为你知道它是异步的.如果您并行运行两个查询,则两者都会同时检查 doc 是否存在,并且两者都会尝试创建记录.

This is very complicated thing to solve with node, as you know its async. If you are running both queries parallel, both will check if doc exists as same time and both will try to create the record.

你可以做两件事.

创建唯一索引

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


使用 $setOnInsert 更新

OR
Use Update with $setOnInsert

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

并确保索引存在于 mongoDB 中.

And Make sure the index exists in mongoDB.

Mongoose 不会修改键集上的索引.首先尝试从 mongo shell 中删除索引.

Mongoose does not modify index on key set. First try to remove index from mongo shell.

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

重启节点进程,mongoose 现在将创建具有唯一约束的索引.

Restart node process and mongoose will now create index with unique constraint.

这篇关于独特的验证在猫鼬中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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