Nodejs UUIDv4 在 Mongoose 中使用时产生常量 id 值 [英] Nodejs UUIDv4 producing constant id value when used in Mongoose

查看:78
本文介绍了Nodejs UUIDv4 在 Mongoose 中使用时产生常量 id 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我注意到我的 UUIDv4 生成器的碰撞率很高.我用它为我的 mongodb 对象生成 UUID,如下所示:

const mongoose = require('mongoose');const uuid = require('uuid/v4');const { 架构 } = 猫鼬;const ObjectSchema = 新架构({UUID: { type: String, required: true, default: uuid() },...})

预期产出

<预><代码>[{UUID:'079f67e1-4532-49fc-b7e6-2e6970c8702f',_id:5e0aa675f900cb561bf51fac,},{UUID:'afbc0fd4-99aa-4d73-88d7-a4724fb3df30',_id:5e0aa675f900cb561bf51fad,},{UUID:'39b099b5-9eaf-4ac3-8d4b-1380369090b5',_id:5e0aa675f900cb561bf51fae,}]

实际结果

<预><代码> [{UUID:'39b099b5-9eaf-4ac3-8d4b-1380369090b5',_id:5e0aa675f900cb561bf51fac,},{UUID:'39b099b5-9eaf-4ac3-8d4b-1380369090b5',_id:5e0aa675f900cb561bf51fad,},{UUID:'39b099b5-9eaf-4ac3-8d4b-1380369090b5',_id:5e0aa675f900cb561bf51fae,}]

我最近注意到的是,它经常给出一个常数值.通常,当我重新启动服务器时会分配一个新值.还有谁有相同的问题吗?

解决方案

你的代码的问题是 UUID 会生成一次,并且会使用相同的默认值.

你需要像这样使用default的函数形式每次生成不同的uuid:

UUID: { type: String, required: true, default: () =>uuid() }

Recently I noticed that my UUIDv4 generator is having a high rate of collision. I use it to generate UUIDs for my mongodb objects like this:

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

const { Schema } = mongoose;

const ObjectSchema = new Schema({
  UUID: { type: String, required: true, default: uuid() },
  ...})

Expected Output

[
  {
    UUID: '079f67e1-4532-49fc-b7e6-2e6970c8702f',
    _id: 5e0aa675f900cb561bf51fac,

  },
  {
    UUID: 'afbc0fd4-99aa-4d73-88d7-a4724fb3df30',
    _id: 5e0aa675f900cb561bf51fad,

  },
  {
    UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
    _id: 5e0aa675f900cb561bf51fae,

  }
]

Actual Result

 [
      {
        UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
        _id: 5e0aa675f900cb561bf51fac,

      },
      {
        UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
        _id: 5e0aa675f900cb561bf51fad,

      },
      {
        UUID: '39b099b5-9eaf-4ac3-8d4b-1380369090b5',
        _id: 5e0aa675f900cb561bf51fae,

      }
    ]

What I noticed recently is that it gives a constant value more often than not. Usually, a new value is assigned when I restart the server. Anyone else having this issue?

解决方案

The problem with your code is UUID will be generated one time, and it will use that same default value.

You need to use function form of default like this to generate a different uuid every time:

UUID: { type: String, required: true, default: () => uuid() }

这篇关于Nodejs UUIDv4 在 Mongoose 中使用时产生常量 id 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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