function generate(count) {
    var founded = false,
        _sym = 'abcdefghijklmnopqrstuvwxyz1234567890',
        str = '';
    while(!founded) {
        for(var i = 0; i < count; i++) {
            str += _sym[parseInt(Math.random() * (_sym.length))];
        }
        base.getID(string, function(err, res) {
            if(!res.length) {
                founded = true; // How to do it?
            }
        });
    }
    return str;
}

如何设置一个变量值与数据库查询回调?我该怎么做呢?


当前回答

节点uuid已弃用,请使用uuid

npm install uuid --save
// Generate a v1 UUID (time-based) 
const uuidV1 = require('uuid/v1');
uuidV1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 

// Generate a v4 UUID (random) 
const uuidV4 = require('uuid/v4');
uuidV4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

Npm链接

其他回答

安装uuid

npm install --save uuid

Uuid被更新,旧的导入

const uuid = require('uuid/v4');

不工作,我们现在应该使用这个导入

const {v4: uuid} = require('uuid');

把它作为一个函数来使用

const  createdPlace = {
    id: uuid(),
    title,
    description,
    location: coordinates,
    address,
    creator
  };

我想用这个

class GUID { Generate() { const hex = "0123456789ABCDEF"; const model = "xxxxxxxx-xxxx-4xxx-xxxx-xxxxxxxxxxxx"; var str = ""; for (var i = 0; i < model.length; i++) { var rnd = Math.floor(Math.random() * hex.length); str += model[i] == "x" ? hex[rnd] : model[i] ; } return str.toLowerCase(); } } console.log(new GUID().Generate()); console.log(new GUID().Generate()); console.log(new GUID().Generate()); console.log(new GUID().Generate()); console.log(new GUID().Generate());

编辑:shortid已弃用。维护者建议使用纳米体代替。


另一种方法是使用npm中的shortid包。

它非常容易使用:

var shortid = require('shortid');
console.log(shortid.generate()); // e.g. S1cudXAF

它有一些引人注目的特点:

ShortId创建惊人的短非顺序url友好的唯一 id。完美的url缩短器,MongoDB和Redis id,和任何其他 用户可能看到的Id。 默认7-14个url友好字符:A-Z, A-Z, 0-9, _- 非连续的,所以它们是不可预测的。 可以生成任意数量的id而不重复,甚至每天数百万。 应用程序可以重新启动任意次数,没有任何重复id的机会。

在Node中创建随机32字符字符串的最快方法是使用本地crypto模块:

const crypto = require("crypto");

const id = crypto.randomBytes(16).toString("hex");

console.log(id); // => f9b327e70bbcf42494ccb28b2d98e00e

安装NPM uuid包(来源:https://github.com/uuidjs/uuid):

npm install uuid

并在你的代码中使用它,例如ES6导入:

import { v4 as uuidv4, v6 as uuidv6 } from 'uuid';

uuidv4();
uuidv6();

或者使用CommonJS需要:

const { 
  v1: uuidv1,
  v4: uuidv4,
} = require('uuid');

uuidv1(); // -> '6c84fb90-12c4-11e1-840d-7b25c5ee775a' 
uuidv4(); // -> '110ec58a-a0f2-4ac4-8393-c866d813b8d1' 

For