Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

259
Vistas
How to generate unique id for each entry in mongoDB?

How do I generate a unique ID for each entry into my mongoDB through Postman?

I run postman POST with http://localhost:8000/api/user/store and send

{
"name":"testname",
"email":"testemail@test.com",
"phone":"testnumber",
"city":"testcity",
}

This gets saved in my mongoDB and shows this in my mongoDB compass

_id:61f7e48f0c651345677b7775
name:"testname"
email:"testemail@test.com"
phone:"testnumber"
city:"testcity"
__v:0

How can I generate a unique ID and add it in between this process such that it gets saved something like this:

_id:61f7e48f0c651345677b7775
uniqueID:68465135
name:"testname"
email:"testemail@test.com"
phone:"testnumber"
city:"testcity"
__v:0

My model userData.js looks like this:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    phone: {
        type: String,
        required: true
    },
    city: {
        type: String,
        required: true
    },
}, { timeStamps: true })

const User = mongoose.model('User', userSchema);
//export model to use in other files
module.exports = User;

This is the snippet from UserController.js on how the data gets saved

// Saves user to the database
const store = (req, res, next) => {
    let user = new User({
        name: req.body.name,
        email: req.body.email,
        phone: req.body.phone,
        city: req.body.city,
    })
    user.save()
        .then(response => {
            res.json({
                message: 'User added successfully!'
            })
        })
        .catch(error => {
            res.json({
                message: 'An error occured!'
            })
        })
}

The uniqueID can be anything I just added numeric as example. But it has to be unique. How can I do this? Any suggestions would be helpful.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

As far as I know, _id (ObjectId) is already unique, and if you want to provide your own _id you just need to set it in the entity.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use _id from MongoDB as it will always be unique if you don't like the format of the MongoDB _id you can change it to nanoid.


Model

With new uniqueId field

import { nanoid } from 'nanoid';

const UserSchema = new mongoose.Schema({
  name: string,
  uniqueId: {
    type: String,
    required: true,
    default: () => nanoid(7),
    index: { unique: true },
  },
  email: String,
  phone: String,
  city: String,
})


You can also just overwrite _id with nanoid so it doesn't create an extra field in your schema

import { nanoid } from 'nanoid';

const UserSchema = new mongoose.Schema({
  _id: {
    type: String,
    default: () => nanoid(),
  },
  name: string,
  email: String,
  phone: String,
  city: String,
})

Controller

// Saves user to the database
const store = async (req, res, next) => {
  const { name, email, phone, city} = req.body;
  try {
    let user = new User({
      name,
      email,
      phone,
      city,
    });
    const savedUser = await user.save();
    return res.json({
      message: 'User added successfully!',
    });
  } catch (error) {
    console.log(error)
    return res.json({
      message: 'An error occured!',
    });
  }
};

about 4 years ago · Juan Pablo Isaza Denunciar

0

The mongodb javascript driver has UUID already:

db.foo.insert( {x: new UUID()} );
db.foo.aggregate([ {$project: {x:true, x_type: {$type: "$x"}}} ]);
{
    "_id" : ObjectId("61f81af6a565bb368b38e345"),
    "x" : UUID("b639a8b5-2598-429f-92e0-630c6b5bfbdc"),
    "x_type" : "binData"
}

If you don't like the actual UUID object then capture its string rep. Note that unfortunately, toString() on the object does not yield 892ab869-3339-41b3-a612-5c29871f4e57 but rather the whole of UUID("892ab869-3339-41b3-a612-5c29871f4e57") so you have to substr it:

db.foo.insert( {x: (new UUID()).toString().substr(6,36) });
db.foo.aggregate([ {$project: {x:true, x_type: {$type: "$x"}}} ]);
{
    "_id" : ObjectId("61f81b56a565bb368b38e348"),
    "x" : "d5af9fb4-768c-4e17-b69a-8bcd80f8bf1e",
    "x_type" : "string"
}

Or, for simplicity you can use the hex() method:

db.foo.insert( {x: (new UUID()).hex() } );
db.foo.aggregate([ {$project: {x:true, x_type: {$type: "$x"}}} ]);
{
    "_id" : ObjectId("61f81ba9a565bb368b38e34e"),
    "x" : "b9810abea4344932b3da15f7f0d58e2c", // note the dashes went away
    "x_type" : "string"
}

In all cases, the driver -- NOT the server -- will create a unique _id if it is not supplied. Creation of a unique id that is not tied to the database (e.g. _id) can be valuable when integrating and moving data around (compare with moving ROWID out of Oracle in a CSV; not very useful). NOTE: The default generated type for _id is ObjectId which is a type in BSON and is not necessarily tied to MongoDB. That said, UUID is still more of a "machine/DB key" as compared to a familiar business key which can be made unique.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda