猫鼬中的唯一索引不起作用 [英] Unique index in mongoose not working

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

问题描述

我正在尝试在猫鼬中为字段("event_key")创建唯一索引,并且如果我尝试创建重复条目,我希望mongodb不保存.我看了看文档,看来我只需要在模式中设置index: {unique: true},但似乎无法使其正常工作.我尝试了几种不同的排列方式,但仍然无法正常工作.

I am trying to create a unique index in mongoose for a field ("event_key"), and I want mongodb to not save if I try to create a duplicate entry. I looked at the docs, and it seems all I need to do is set index: {unique: true} in the schema, but I can't seem to get it to work. I've tried several different permutations and still can't get it to work.

此外,required: true似乎也不起作用,因为即使我不传递event_key也可以保存条目.我可能想念一些真正愚蠢的东西,想知道是否有人可以提供帮助?

In addition, required: true doesn't seem to be working too since I can save an entry even if I do not pass in an event_key. I'm probably missing something really stupid, and wondering if anyone can help?

模式

var WistiaAnalyticSchema = new Schema({
  event_key: {type: String, required: true, index: {unique: true}},
  visitor_key: String,
  created: {type: Date, default: Date.now},
  ip: String,
})

尝试添加到数据库

WistiaAnalytic.create({event_key: '1402230270487e0.2668362990953028'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({ip: '1402229819163e0.4385743956081569'}, function(err) {});
WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {
  console.log(err)
});

推荐答案

猫鼬在后台创建索引,因此您需要将create调用延迟到索引创建完成之前.一种实现方法是使用模型的'index'事件:

Mongoose creates indexes in the background, so you need to delay your create calls until index creation has completed. One way to do that is with the 'index' event of the model:

WistiaAnalytic.on('index', function(err) {
    WistiaAnalytic.create({event_key: '1402230270487e0.2668362990953028'}, function(err) {});
    WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {});
    WistiaAnalytic.create({ip: '1402229819163e0.4385743956081569'}, function(err) {});
    WistiaAnalytic.create({event_key: '1402229819163e0.4385743956081569'}, function(err) {
      console.log(err)
    });
});

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

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