Mongodb - mongoose autoincrement custom ID JS - javascript

I'm working on a membership admin pannel and I'm required to do a custom membership ID asides from the _id itself.
My schema is actually looking like this:
const mongoose = require("mongoose");
const memberSchema = mongoose.Schema(
{
membershipId: {
/* AutoIncrement custom id */
type: Number,
default: 1,
unique: true,
index: true,
autoIncrement: true,
},
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
},
{
timestamps: true,
}
);
const Member = mongoose.model("Member", memberSchema);
module.exports = Member;
the point is that I would like to have something standarized by the company, such as... EMP-00001, EMP-000002, that autoincrements.
Is it possible? If so, how can I achieve this?
Thank you in advance.

Related

Monogo DB Schema

I needed a property of date/time which would allow to me get the time at which a certain task was created, I added timestamp property and set it to be true,
But I m not able to compile my code.
The code is perfectly running fine without the timestamp property
const mongoose = require("mongoose");
const Task = mongoose.model(
"Task",
({
title: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
minLength: 100,
},
completed: {
type: Boolean,
default: false,
},
},
{ timestamps: true })
);
module.exports = Task;
I needed a property of date/time which would allow to me get the time at which a certain task was created, I added timestamp property and set it to be true,
But I m not able to compile my code.
The mongoose.model() function of the mongoose module is used to create a collection of a particular database of MongoDB. The name of the collection created by the model function is always in plural format mean GFG to gfss and the created collection imposed a definite structure.
Syntax:
mongoose.model(<Collectionname>, <CollectionSchema>)
Parameters: This function accepts the following two parameters:
Collection name: It is the name of the collection.
Collection Schema: It is the schema of the collection.
Return type: This function returns the Mongoose object.
You need to pass a valid schema for the second argument like below
const mongoose = require("mongoose");
const TodoModel = mongoose.model(
"Task",
new mongoose.Schema(
{
title: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
minLength: 100,
},
completed: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
)
);
module.exports = TodoModel;
More about what is a valid schema refer below
https://mongoosejs.com/docs/schematypes.html

Calculate Leaderboard Ranking and Point System for Users in React Js Javascript MongoDB

I am creating a MERN Stack Application which gives 'Points' to a User based on how many Posts, Comments and Likes they do.
I need to generate a LEADERBOARD from this, that Ranks all the Users (User with the most Posts, Comments & Likes) and also shows the sum count of Post, Comments & Likes.
Currently I have a userSchema as per below:
import mongoose from 'mongoose'
const { Schema } = mongoose
const userSchema = new Schema(
{
name: {
type: String,
trim: true,
required: true,
},
email: {
type: String,
trim: true,
required: true,
unique: true,
},
const postSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
title: {
type: String,
required: true,
},
comments: [
{
content: 'String',
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
},
],
likes: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
},
],
}
);
How do I list out in a LEADERBOARD all the Users and Rank them based on their TOTAL POINTS (sum of number of posts, comments & likes)?

How to request for "like" for the function "populate"

I would like to retrieve with a search field the channels according to the user's first name.
const UserSchema = new mongoose.Schema({
email: {
type: String,
require: true,
trim: true,
unique: true
},
password: {
type: String,
require: true,
trim: true,
unique: true
},
_profile: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Profile',
require: true,
unique: true
}
})
const ProfileSchema = new mongoose.Schema({
name: {
type: String,
require: true,
trim: true,
unique: true
},
firstname: {
type: String,
require: true,
trim: true,
unique: true
}
})
const ChannelSchema = new mongoose.Schema({
title: {
type: String,
require: true,
trim: true,
unique: true
},
_user: {
type: String,
require: true,
trim: true,
unique: true
}
})
const User = mongoose.model('User', UserSchema)
const Profile = mongoose.model('Profile', ProfileSchema)
const Channel = mongoose.model('Channel', ChannelSchema)
I used to populate function to retrieve the data from the joins
let ChannelSearch = await Channel
.find()
.populate({
path: '_user',
select:'-password',
populate: {
path: '_profile'
}
})
but where I block is how to retrieve the channels based on the user's first name
I can't seem to find how it is possible to make a like request through the populate function
Thank you in advance for your help !! =)
you can your regex to find your data.
let ChannelSearch = await Channel
.find({firstname: /regex/})
.populate({
path: '_user',
select:'-password',
populate: {
path: '_profile'
}
})
or use $regex in yout mongo query.
https://docs.mongodb.com/manual/reference/operator/query/regex/
I believe this is not possible, in the mongoose documentation it is put this:
In general, there is no way to make populate() filter stories based on properties of the story's author. For example, the below query won't return any results, even though author is populated.
const story = await Story.
findOne({ 'author.name': 'Ian Fleming' }).
populate('author').
exec();
story; // null
If you want to filter stories by their author's name, you should use denormalization.

Student, teacher one common model or two separate ones in mongoose?

I need to create an account for a student and a teacher. Should I create two separate models in mongoose for student and teacher? What's the right approach? Student and teacher will share some properties and some will differ.
At this moment I have only one model for student and tutor:
const userSchema = new Schema({
name: {
type: String,
trim: true,
required: true,
maxLength: 32
},
surname: {
type: String,
trim: true,
required: true,
maxLength: 32
},
email: {
type: String,
unique: true,
trim: true,
required: true,
lowercase: true
},
isActiveTutor: {
type: Boolean,
default: false
},
birthCountry: String,
initials: String,
hashed_password: {
type: String,
required: true
},
salt: String,
role: {
type: String
},
teachingLanguage:{
type: Object,
/*language: {
language,
level,
price
}*/
},
resetPasswordLink: {
data: String,
default: ''
}
}, {timestamps: true});
But what if I wanted to give a teacher properties that a student would not have?
In case someone pass by here.
const options = {discriminatorKey: 'kind'};
const userSchema = new mongoose.Schema({/* user schema: (Common) */}, options);
const User = mongoose.model('User', userSchema);
// Schema that inherits from User
const Teacher = User.discriminator('Teacher',
new mongoose.Schema({/* Schema specific to teacher */}, options));
const Student = User.discriminator('Student',
new mongoose.Schema({/* Schema specific to student */}, options));
const teacher = new Teacher({/* */});
const student = new Student({/* */});
Original answer(modified): here.
Have a look at the docs here.

How can I define a field with a range of data in mongoose schema?

My current Mongoose Schema is this:
const mongoose = require('mongoose');
const resultSchema = new mongoose.Schema({
scores: { type: Number, required: true },
analysis: { type: String, required: true }
},
{ timestamps: true, toJSON: { virtuals: true } }
);
module.exports = mongoose.model('Result', resultSchema);
And I want that scores field has a range of numbers. For example 100 to 500.
What should I do?
Meanwhile, Can I use MongoDB operator in Mongoose?
Mongoose has several built-in validators to satisfy exactly this use case.
Since scores is of type Number, you can use the min and max validators to validate a range in this manner:
const mongoose = require('mongoose');
const resultSchema = new mongoose.Schema({
scores: {
type: Number,
required: true,
min: 100,
max: 500
},
analysis: {
type: String,
required: true
}
}, { timestamps: true, toJSON: { virtuals: true } });
module.exports = mongoose.model('Result', resultSchema);
You can read about validation in Mongoose: https://mongoosejs.com/docs/validation.html

Categories