Home > Blockchain >  How to generate unique id for each entry in mongoDB?
How to generate unique id for each entry in mongoDB?

Time:01-31

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":"[email protected]",
"phone":"testnumber",
"city":"testcity",
}

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

_id:61f7e48f0c651345677b7775
name:"testname"
email:"[email protected]"
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:"[email protected]"
phone:"testnumber"
city:"testcity"
__v:0

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.

CodePudding user response:

As I know _id is already unique, and if you want to provie own _id you just need to set it in the entity.

CodePudding user response:

You can use the nanoid package to do that https://github.com/ai/nanoid

in your model

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

in controller

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

CodePudding user response:

You can't generate unique id technically but it has to be big enough to not generate the same id, example:

function create_UUID(){
    var dt = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (dt   Math.random()*16) | 0;
        dt = Math.floor(dt/16);
        return (c=='x' ? r :(r&0x3|0x8)).toString(16);
    });
    return uuid;
}

Output:

1fe35579-5ce7-46ec-89e0-7e7236700297

Source:

https://www.w3resource.com/javascript-exercises/javascript-math-exercise-23.php

  •  Tags:  
  • Related