Node.js:Mongoose 模式默认兰特令牌不是随机的

问题描述 投票:0回答:3

我有一个像这样的

UserSchema
,但我似乎无法生成独特的随机
activation_token

我正在使用

rand-token
进行生成。 在这里找到

 var UserSchema = new Schema({
        activation_token: {
            type: String,
            default: randToken.generate(64),
        },
        email: {
            type: String,
            unique: true,
            sparse: true
        },
        first_name: {
            type: String
        },
        last_name: {
            type: String
        }
});

看起来工作正常,但是当使用 Mocha 运行单元测试时,所有

activation_token
字段都是相同的。我最初认为这与时间有关,因为这可能是用来生成令牌的。对于每个新文档,时间戳可能是相同的,因此我使用一个函数运行了一些测试,该函数依次生成了大约 30 个令牌,并且它们相似。

对这里发生的事情有什么想法吗?

以下是问题的一些示例:

{
    "_id": {
        "$oid": "555dfd137c914edc1b41bbda"
    },
    "email": "[email protected]",
    "first_name": "Lenora",
    "last_name": "Aguilar",
    "date_added": {
        "$date": "2015-05-21T15:43:01.576Z"
    },
    "activation_token": "EyBNwu4vxOIXMzj7W5kVOeICfWwxfjXmHkz7ZPHLjkf0MU86QM2aIKNDyvI2YmTR",
    "__v": 0
},
{
    "_id": {
        "$oid": "555dfd107c914edc1b41bbd6"
    },
    "email": "[email protected]",
    "first_name": "Eugene",
    "last_name": "Green",
    "date_added": {
        "$date": "2015-05-21T15:43:01.576Z"
    },
    "activation_token": "EyBNwu4vxOIXMzj7W5kVOeICfWwxfjXmHkz7ZPHLjkf0MU86QM2aIKNDyvI2YmTR",
    "__v": 0
}
node.js mongodb random default uid
3个回答
18
投票

它们都是一样的,这是有道理的。您在模式定义时调用

generate
一次,并将该调用的 result 提供给猫鼬模式定义,而不是函数本身。你可以尝试这样的事情:

var UserSchema = new Schema({
    activation_token: {
        type: String,
        default: function() {
            return randToken.generate(64);
        }
    },
    email: {
        type: String,
        unique: true,
        sparse: true
    },
    first_name: {
        type: String
    },
    last_name: {
        type: String
    }
});

0
投票

您可以使用 https://www.npmjs.com/package/uuid 包,例如:

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

const UserSchema = new Schema({
        activation_token: {
            type: String,
            default: uuidv4(),
        },
        email: {
            type: String,
            unique: true,
            sparse: true
        },
        first_name: {
            type: String
        },
        last_name: {
            type: String
        }
});

UUID 标准旨在防止冲突并在同一系统上仅生成安全(防止占卜)的唯一 ID。


-2
投票
npm install rand-token --save

安装节点包,

const randtoken = require('rand-token');

导入js文件并生成token

const a = randtoken.generate(256
);

© www.soinside.com 2019 - 2024. All rights reserved.