Mongodb在架构级别生成默认随机数将生成相同的数字 [英] Mongodb generating default random numbers in schema level is generating same numbers

查看:395
本文介绍了Mongodb在架构级别生成默认随机数将生成相同的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将mongodb用作数据库,而将mongoose用作ORM.我的架构中有一个字段Booking_id是唯一的,所以我不能将其为null.因此,我将代码设计如下.

I am using mongodb as database with mongoose as ORM. I have a field booking_id in my schema which is unique , so I cannot have it null. Thus I have designed my code something like this.

  var bookingSchema = new Schema({
    booking_id_customer: {
        type: Number,
        default : Math.floor(Math.random()*900000000300000000000) + 1000000000000000,
        index: { unique: true }
    },

这是第一次完美运行,但是从第二次开始,我就收到了重复性错误.

It works perfectly for the first time, but from 2nd time onwards I get this duplicacy error.

    { [MongoError: E11000 duplicate key error index: xx.bookings.$booking_id_customer_1 dup key: { : 4.439605615108491e+20 }]
  name: 'MongoError',
  message: 'E11000 duplicate key error index:

我希望它会生成随机数,但是我不知道第二次出了什么问题.

I expect it to generate random numbers but I have no clue about whats going wrong in 2nd time.

推荐答案

在架构创建时,您只需设置一次默认值即可.

You are setting the default just once, at schema creation.

如果要为每个新文档调用它,则需要将其转换为Mongoose将调用的函数:

If you want it to be called for each new document, you need to turn it into a function that Mongoose will call:

default : function() {
  return Math.floor(Math.random()*900000000300000000000) + 1000000000000000
}

但是,您的代码还有另一个问题:您使用的值(900000000300000000000和1000000000000000)超过了

However, there is another issue with your code: the values you're using (900000000300000000000 and 1000000000000000) exceed Number.MAX_SAFE_INTEGER, which can lead to problems.

我建议使用mongoose.Types.ObjectId作为id生成器,这也是Mongoose和MongoDB用于创建(唯一)文档ID的内容:

I would suggest using mongoose.Types.ObjectId as id generator, which is also what Mongoose and MongoDB use to create (unique) document id's:

booking_id_customer : {
  type    : mongoose.Schema.Types.ObjectId,
  default : mongoose.Types.ObjectId,
  index   : { unique: true }
}

或重新使用文档的_id属性,该属性也是唯一的.

Or re-use the _id property of the document, which is also unique.

这篇关于Mongodb在架构级别生成默认随机数将生成相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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