ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript
https://zelark.github.io/nano-id-cc/
MIT License
24.61k stars 790 forks source link

Generates Duplicate keys and throws errors when used with mongodb (mongoose) #344

Closed sanjeevrouhan closed 2 years ago

sanjeevrouhan commented 2 years ago

Showing error E11000 duplicate key error collection: mongodb_example.users index: _id_ dup key: { _id: \"RXtVE_W9hEAVg8c6Os1wO\" }

Here is my Model code used for _id

`import { nanoid } from "nanoid"; import { Schema, model } from "mongoose";

const UserSchema = new Schema({ _id: { type: String, default: nanoid(), }, firstName: { type: String, required: true, }, lastName: { type: String, required: false, }, email: { type: String, required: true, }, password: { type: String, required: true, }, }); `

ai commented 2 years ago

Sorry, I do not use Mangoose to help you here.

Every ID is very unique with default settings. There could be done problem with Mangoose config.

AlexBollmann commented 1 year ago

Hi @sanjeevrouhan

Had the same problem, turns out you would have to write it as lambda:

_id: { type: String, default: () => nanoid() }

If you don't, it will create the same id over and over..