在 mongoose 中,”Unique” 不按预期工作。

huangapple go评论65阅读模式
英文:

Unique in mongoose not working as expected

问题

以下是您要翻译的内容:

我有一个示例的mongoose模式如下

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const exampleSchema = new Schema ({
    name:{
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    mobile:{
        type: String,
        required: true,
        unique: true
    }
})

module.exports ={Driver: mongoose.model('Driver', driverSchema)}
现在的问题是手机上的唯一性正常工作但在电子邮件中允许我插入重复的电子邮件地址
英文:

I have my example mongoose schema as below

 const mongoose = require('mongoose')
 const  Schema = mongoose.Schema

 const exampleSchema = new Schema ({
        name:{
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true,
            unique: true
        },
        mobile:{
            type: String,
            required: true,
            unique: true
        }
    })

 module.exports ={Driver: mongoose.model('Driver', driverSchema)}

Now the thing is that unique in mobile is working fine, but in email it allows me to insert duplicate email address.

答案1

得分: 1

你最好在mongodb shell中创建你的索引。

mongoose文档中,他们提到:

> 在生产环境中,你应该使用MongoDB shell来创建你的索引,而不是依赖mongoose来为你做这个。模式的唯一选项在开发和文档编写方面很方便,但mongoose不是索引管理解决方案。

因此,我会从模式中移除唯一选项,然后可以像这样在mongodb shell中创建唯一索引:

db.drivers.createIndex( { "email": 1 }, { unique: true } )
db.drivers.createIndex( { "mobile": 1 }, { unique: true } )
英文:

You had better to create your indexes in mongodb shell.

In the mongoose docs they state:

> 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.

So I would remove unique options in schema, and can create the unique indexes in mongodb shell like this:

db.drivers.createIndex( { "email": 1 }, { unique: true } )
db.drivers.createIndex( { "mobile": 1 }, { unique: true } )

答案2

得分: 0

这是由于在添加 unique: true 之前,我在集合中有记录。

英文:

It was due to I have records in collection before giving unique: true.

huangapple
  • 本文由 发表于 2020年1月3日 18:42:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定