在Mongo中稳健地检索哪个字段警告“重复键错误" [英] Robustly retrieve which field caued 'duplicate key error' in Mongo

查看:74
本文介绍了在Mongo中稳健地检索哪个字段警告“重复键错误"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,mongo在代码11000或11001上引发诸如以下错误消息:

So, mongo throws an error-message such as the following on code 11000 or 11001:

{ [MongoError: E11000 duplicate key error index: mean-dev.users.$username_1  dup key: { : "asdasd" }]
  name: 'MongoError',
  err: 'E11000 duplicate key error index: mean-dev.users.$username_1  dup key: { : "asdasd" }',
  code: 11000,
  n: 0,
  connectionId: 718,
  ok: 1 }

现在,我正在解析错误消息以检索哪个字段具有重复的密钥,该密钥非常脏.即:我不想测试不同索引(多键,复合键等)上的所有重复错误,以查看此解析器是否仍然有效.

Right now, I'm parsing the error-message to retrieve which field has a duplicate key, which is incredibly dirty. i.e: I don't want to test all kinds of duplicate errors on different indices (multikey, compound, etc) to see if this parser still works.

我可以使用Node中的任何帮助程序,让我稳健地检索此类错误的违规字段吗?

Any helpers in Node that I could use, that let me robustly retrieve the offending field for such errors?

推荐答案

如果您想查看索引的实际键,而不是解析不可靠的字符串,则可以像这样简单地查询system.indexes集合:

If you want to see the actual keys for an index, rather than parsing an unreliable string, you can simply query the system.indexes collection like this:

db.collection('system.indexes').findOne({ ns: 'mean-dev.users', name: 'username_1' }, cb);

这将导致文档包含一个键对象,列出组成该索引键的所有字段名称,例如:

Which should result in a document containing a key object, listing of all the field names that make up this index key, e.g.:

{
  v: 1,
  ns: 'mean-dev.users',
  name: 'username_1',
  key: {
    username: 1
  }
}

这篇关于在Mongo中稳健地检索哪个字段警告“重复键错误"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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