猫鼬模式:“独特"不被尊重 [英] Mongoose schema: 'unique' not being respected

查看:21
本文介绍了猫鼬模式:“独特"不被尊重的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Mongoose 与此架构一起使用

I'm trying to use Mongoose with this schema

var RestoSchema = new Schema({
    "qname"          : {type: String, required: true, unique: true},
    ...
});

问题是这仍然允许使用现有的 qname 创建数据库的新条目.从我在下面看到的索引已经创建,但是当我使用 .save 方法时没有任何明显的影响.我有什么误解?

The problem is that this still permits new entries to the database to be created with an existing qname. From what i can see below the index has been created, but without any demonstrable impact when I use the .save method. What am I misunderstanding?

> db.restos.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "ns" : "af.restos",
        "name" : "_id_"
    },
    {
        "v" : 1,
        "key" : {
            "qname" : 1
        },
        "ns" : "af.restos",
        "name" : "qname_1",
        "background" : true,
        "safe" : null
    }
]

推荐答案

getIndexes 输出显示 qname 上的索引不是作为唯一索引创建的.Mongoose 不会更改现有索引,因此您必须手动删除该索引,然后重新启动您的应用,以便 Mongoose 可以将其重新创建为唯一的.

The getIndexes output shows that the index on qname wasn't created as a unique index. Mongoose doesn't alter an existing index, so you'll have to manually drop the index and then restart your app so that Mongoose can re-create it as unique.

在外壳中:

db.restos.dropIndex('qname_1')

这篇关于猫鼬模式:“独特"不被尊重的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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