Node.js + Mongoose/Mongo &缩短的 _id 字段 [英] Node.js + Mongoose / Mongo & a shortened _id field

查看:61
本文介绍了Node.js + Mongoose/Mongo &缩短的 _id 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的一个模型中的唯一 _id 字段相对较短:8 个字母/数字,而不是通常更长的 Mongo _id.像这样的简短唯一索引在我的代码中的其他地方有帮助,出于某些原因,我将在这里跳过.我已经成功创建了一个模式来完成这个技巧(randomString 是一个生成给定长度的字符串的函数):

I'd like the unique _id field in one of my models to be relatively short: 8 letters/numbers, instead of the usual Mongo _id which is much longer. Having a short unique-index like this helps elsewhere in my code, for reasons I'll skip over here. I've successfully created a schema that does the trick (randomString is a function that generates a string of the given length):

new Schema('Activities',  {
    '_id': { type: String, unique: true, 'default': function(){ return randomString(8); } },   
    // ... other definitions
}

到目前为止效果很好,但我担心从 randomString 函数生成的重复 ID.有 36^8 个可能的 ID,所以现在这不是问题……但是随着可能的 ID 集填满,我担心插入命令会因 ID 重复而失败.

This works well so far, but I am concerned about duplicate IDs generated from the randomString function. There are 36^8 possible IDs, so right now it is not a problem... but as the set of possible IDs fills up, I am worried about insert commands failing due to a duplicate ID.

显然,我可以做一个额外的查询来检查 ID 是否在执行插入之前被占用......但这让我内心哭泣.

Obviously, I could do an extra query to check if the ID was taken before doing an insert... but that makes me cry inside.

我确信有更好的方法可以做到这一点,但我没有在文档中看到它.

I'm sure there's a better way to be doing this, but I'm not seeing it in the documentation.

推荐答案

通过在 _id 上创建唯一索引,如果您尝试插入具有重复键的文档,您将收到错误消息.因此,围绕您执行的任何查找错误的插入进行错误处理,然后生成另一个 ID 并在这种情况下重试插入.您可以在您的架构中添加一个 method 来实现这种增强的保存,以保持干净和干燥.

By creating a unique index on _id you'll get an error if you try to insert a document with a duplicate key. So wrap error handling around any inserts you do that looks for the error and then generates another ID and retries the insert in that case. You could add a method to your schema that implements this enhanced save to keep things clean and DRY.

这篇关于Node.js + Mongoose/Mongo &缩短的 _id 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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