Reputation: 98
In my documents, I have 3 fields in that docs and now I want to create sequential user id which is auto-generated like we set joining_id as the prefix for all user id prefix then all user id start with that prefix like
user 1 id is = joining_id1
, user 2 id is = joining_id2
so on .... like this
my code is
const tourSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A User must have name'],
unique: true
},
joining_id: {
type: String
},
reffral_id: {
type: Number,
required: [true, 'A user must have a Reffral Id']
}
});
Upvotes: 0
Views: 909
Reputation: 285
My opinion is before store user query to your database and gets the length of your current collection then add 1 to that length.
const addUser = async () => {
const totalUsers = await db.collection.count();
const newUser = {
_id: `joining_id${totalUsers + 1}`,
...other keys
}
const user = await db.collection.insertOne(newUser)
}
May be this will help.
Upvotes: 1