简体   繁体   English

如何在 MongoDB 中创建自定义 ID

[英]How to create a custom id in MongoDB

I want to create a custom id in MongoDB.我想在 MongoDB 中创建一个自定义 ID。

Example- suppose I have a user document and in which the custom id should contain, first two letters of country code then after that two letters of state code then a random unique number.示例 - 假设我有一个用户文档,其中自定义 ID 应包含前两个国家代码字母,然后是两个国家代码字母,然后是一个随机的唯一数字。

Example: suppose the user is from India and the state is delhi so the id should look like this - INDL123示例:假设用户来自印度,州是德里,因此 id 应如下所示 - INDL123

I am using NodeJS.我正在使用 NodeJS。

You can create a property in your Schema named CustomID or whatever you want to name it and make it of type string , then you can use the function below to Generate the CustomID based on country,city passed.您可以在您的架构中创建一个名为CustomID的属性或任何您想要命名的属性并将其CustomID string类型,然后您可以使用下面的函数根据传递的country,city生成 CustomID。

This is just a quick example and can be improved a lot这只是一个简单的例子,可以改进很多

 let country = 'India' let city = 'Delhi' function CreateCustomID(country, city) { return `${country.slice(0, 2).toUpperCase()}${city.slice(0,2).toUpperCase()}${Math.floor(Math.random()*(999-100+1)+100)}` } console.log(CreateCustomID(country, city))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM