MongoDB Schema for interview time slot availability - javascript

I'm building a website where admins can create interviews by selecting participants,
interview start time and end time. I have divided the participants into two groups(collections) - Applicants and Team_Members.
I tried creating a 3rd collection called Interviews to keep track of the start and end times for each interview but I don't think that there's a need for a 3rd collection now.
So far, these are the schemas I have come up with -
const applicantSchema = new Schema({
name: {
type: String,
trim: true,
required: [true, "Name is required"],
},
image: {
type: String,
},
interviews: [
{
start_time: String,
end_time: String,
},
],
});
const interviewerSchema = new Schema({
name: {
type: String,
trim: true,
required: [true, "Name is required"],
},
image: {
type: String,
default: "download.png",
},
interviews: [{
start_time: String,
end_time: String,
}, ],
});
How should I update the interviews property once each new interview is booked? And am I going in the right direction in terms of forming the schemas for the problem required?

You could use the same schema for both. Just add interviewee: { type: boolean, required: true } and add that criteria when you do a search.
for the interviews start and end times, change the values to Date, like that you will be able to search them and find dates > $gt or < $st to make sure you don't double book a time slot. For marking booked, simply add another value called `booked: { type: boolean, default: false'
const interviewSchema = new Schema({
name: {
type: String,
trim: true,
required: [true, "Name is required"],
},
image: {
type: String,
},
interviewee: {
type: Boolean,
required: true
},
interviews: [
{
start_time: {
type: Date,
default: new Date()
},
end_time: {
type: Date,
default: new Date()
},
booked: {
type: Boolean,
default: false
}
},
],
});

Related

mongoose how to take dates between two

I have project - renting app. I need to decide if car is available in dates between date_finish and date_start (includes that dates). I have model - car and order. Orders have few fields: dateStart and dateFinish, carId
How to take only these carIds that are available between start_date and stop_date (including these 2 days).
Car:
mark:{
type: String,
required: true,},
model:{
type: String,
required: true,},
price:{
type: Number,
required: true,},
available: {
type: Boolean,
required: true,},
pic_1:{
type:String,
required:true,
},
pic_2:{
type:String,
required:true,
},
},
{ collection: 'cars' }
)
Order:
const orderSchema = new mongoose.Schema(
{
userID: { type: String, required: true },
carID: { type: String, required: true },
status: {type:String,required:true},
dateStart: {type:Date,required:true},
dateFinish:{type:Date,required:true},
total: {type:Number,required:true},
},
{ collection: 'orders' }
)
Status:1 for new orders, 2 for orders durating now, 3 for archive/completed orders
mongoose query:
var orders_n = await Order.find({"status":{'$lte':"2"},$and[{"dateFinish":{ '$lte': start},"dateStart":{}}]"dateFinish":{ '$lte': start}}).select('carID -_id').exec();
That query doesn't work. Who can help me?
EDIT: I have to (firstly) take orders which :
-date of start and date of end are greater than passed by user date of end
-date of end is lower than passed by user date of start.
In other words - I need cards available in days between passed dates.
Try pass dates this way: var orders_n = await Order.find({"status":{'$lte':"2"},$and[{"dateFinish":{ '$gte': new Date()},"dateStart":{ '$lte': new Date()}}]}).select('carID -_id').exec();

How can I create a schema for timetables in MongoDB that is part of a Teacher Schema?

This is my first post at StackOverFlow and I am coming here to search for some ideas to a project that I am developing.
First of all I have one problem of storing available days at a Teacher Schema, in this aplication a Teacher have his class information and it includes availableDays that represents the days and hours available to Students schedule a class with this Teacher, which can be seen below:
const teacherSchema = new mongoose.Schema({
classPrice: {
type: Number,
required: false,
},
education: {
type: [String],
required: false,
},
degree: {
type: String,
required: false,
},
availableDays: {
sunday: {
type: [String],
required: false
},
monday: {
type: [String],
required: false
},
tuesday: {
type: [String],
required: false
},
wednesday: {
type: [String],
required: false
},
thursday: {
type: [String],
required: false
},
friday: {
type: [String],
required: false
},
saturday: {
type: [String],
required: false
},
},
subjects: {
type: [mongoose.Schema.Types.ObjectId],
ref: 'Subject',
required: true,
},
approved: {
type: Boolean,
default: false
},
rating: {
type: Number,
default: 10
}
});
That was a "bad" solution to store availableDays. Saving a String Array of schedules.
The idea was save this data like this:
sunday: ["08:00", "09:00", "10:00"],
monday: ["11:00", "12:00", "13:00"],
...
I am facing some problems at the entire structure.
When a student select a day, for example: (2020/03/02) - (AAAA/DD/MM). It represents a Wednesday, but at my schema there are no diferences between (2020/03/02) and (2020/10/02).
When a student select a day and a hour to schedule his class. This timestamp should be unavailable to others students, and it doesn't occurs.
I also have other Schema to specify the Class:
const classSchema = mongoose.Schema({
teacherId:{
type: String,
required: true,
},
userId: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
****
time:{
type: Number,
required: true,
},
day:{
tipe: String,
required: true,
},
*****
status:{
accepted: {
type: Boolean,
default: false,
},
payment: {
type: Boolean,
default: false,
},
available: {
type: Boolean,
default: false,
}
}
});
Is this Schema, day and time is the DAY and HOUR that student select from AvailableDays at Teacher Schema.
I am looking for some solution that allows the Teacher to select his own day and hours available to be scheduled. This days and hours can be updated by the Teacher at Profile Edit page.
Everything can be changed since I am at the beginning of this project, and I appreciate any help.
For a complete understanding about this problem.
In frontend we are saving the day / time information at Teacher register page like this: Screenshot1
And the student selection is made like this: Screenshot2
After a month I found the solution.
At first I create a new Schema on Mongo called "Agenda".
That agenda has:
{
teacherId: mongoose.Schema.Types.ObjectId,
date: Date(),
availability: true
}
In that way my teacher creates a lot of "Agendas" which represents the distinct schedule with singular times. And that's it

How to optimize performance with CREATE, PUT, and DELETE requests on MongoDB?

I have a database named "reviews" with a 9.7GB size. It has a collection name products. I was able to optimize the READ request using indexing technical by running the command db.products.ensureIndex({product_name: 1}); When I run the following command db.products.find({product_name:"nobis"}).explain("executionStats"); in MongoDB terminal, it shows that my execution time reduces from 28334ms to 3301ms.
I have the following 2 questions:
1) How do I use explain("executionStats"); on CREATE, PUT and DELETE requests? For example, I got this following error [thread1] TypeError: db.products.insert(...).explain is not a function when I tried to use the following insert function
db.products.insert({"product_id": 10000002,"product_name": "tissue","review": [{"review_id": 30000001,"user": {"user_id": 30000001,"firstname": "Peter","lastname": "Chen","gender": "Male","nickname": "Superman","email": "hongkongbboy#gmail.com","password": "123"},"opinion": "It's good","text": "It's bad","rating_overall": 3,"doesRecommended": true,"rating_size": "a size too big","rating_width": "Slightly wide","rating_comfort": "Uncomfortable","rating_quality": "What I expected","isHelpful": 23,"isNotHelpful": 17,"created_at": "2007-10-19T09:03:29.967Z","review_photo_path": [{"review_photo_id": 60000001,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}, {"review_photo_id": 60000002,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}]}, {"review_id": 30000002,"user": {"user_id": 30000002,"firstname": "Peter","lastname": "Chen","gender": "Male","nickname": "Superman","email": "hongkongbboy#gmail.com","password": "123"},"opinion": "It's good","text": "It's bad","rating_overall": 3,"doesRecommended": true,"rating_size": "a size too big","rating_width": "Slightly wide","rating_comfort": "Uncomfortable","rating_quality": "What I expected","isHelpful": 23,"isNotHelpful": 17,"created_at": "2007-10-19T09:03:29.967Z","review_photo_path": [{"review_photo_id": 60000003,"review_photo_url": "https://sdcuserphotos.s3.us-west-1.amazonaws.com/741.jpg"}]}]}).explain("executionStats");
2) Is there any performance Optimization method I can use for the CREATE, PUT and DELETE requests? For example, I am able to use POSTMAN to get the response time of a DELETE request, but the response time takes 38.73seconds.
const deleteReview = (request, response) => {
const id = parseInt(request.params.id);
Model.ProductModel.findOneAndDelete({ "review.review_id": id}, (error, results) => {
if (error) {
response.status(500).send(error);
} else {
response.status(200).send(results);
}
});
};
This is my MongoDB schema:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/reviews', { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true });
const Schema = mongoose.Schema;
const productSchema = new Schema({
product_id: { type: Number, required: true, unique: true },
product_name: { type: String, required: true, unique: true },
review: [{
review_id: { type: Number, required: true, unique: true },
user: {
user_id: { type: Number },
firstname: { type: String },
lastname: { type: String },
gender: { type: String, enum: ['Male', 'Female', 'Other'] },
nickname: { type: String },
email: { type: String, required: true },
password: { type: String, required: true },
},
opinion: { type: String, required: true },
text: { type: String },
rating_overall: { type: Number, min: 1, max: 5, required: true },
doesRecommended: { type: Boolean, required: true },
rating_size: { type: String, enum: ['a size too small', '1/2 a size too small', 'Perfect', '1/2 a size too big', 'a size too big'], required: true },
rating_width: { type: String, enum: ['Too narrow', 'Slightly narrow', 'Perfect', 'Slightly wide', 'Too wide'], required: true },
rating_comfort: { type: String, enum: ['Uncomfortable', 'Slightly uncomfortable', 'Ok', 'Comfortable', 'Perfect'], required: true },
rating_quality: { type: String, enum: ['Poor', 'Below average', 'What I expected', 'Pretty great', 'Perfect'], required: true },
isHelpful: { type: Number, required: true, default: 0 },
isNotHelpful: { type: Number, required: true, default: 0 },
created_at: { type: Date, required: true },
review_photo_path: [{
review_photo_id: { type: Number },
review_photo_url: { type: String }
}]
}]
});
const ProductModel = mongoose.model('product', productSchema);
module.exports = { ProductModel };
If you do not have one, ensure you have an index of review.review_id on your products collection. You're using that to look up what to delete so it should be indexed.
I read your deleteReview function as deleting the product document that contains the review, not just removing the individual review -- is that what you expect?
You should be able to just $pull the review from the reviews array to get rid of it.
You can use explain on an update like so:
db.products.explain().update({...}, {...});
See: https://docs.mongodb.com/manual/reference/method/db.collection.explain/
You can explain:
aggregate()
count()
find()
remove()
update()
distinct()
findAndModify()

MongoDB data modelling performance

I'm currently trying to figure out at mongodb what's the best way in terms of performance cost and redundancy the best way of building a big document data schema. The final JSON from my rest -> app will be likely how it is structured.
Now internally the data will not be used as many to many that's why i binded it into a single document. Only the id will be used as a reference in another collections.
What you guys think, is it better to spit as relational way, with multiple collection to store the content inside of deliverable and use reference or just embedded. (since NoSQL has no joins i though this way will speed up)
Current using mongoose at node app
The Schema:
projectSchema = new Schema({
name: {
type: String,
required: true,
minlength: 3,
maxlength: 50
},
companyId: {
type: mongoose.Types.ObjectId,
ref: 'companies',
required: true
},
deleted: {
type: Number,
enum: [0, 1],
default: 0
},
predictedStartDate: {
type: Date,
default: ""
},
predictedEndDate: {
type: Date,
default: ""
},
realStartDate: {
type: Date,
default: ""
},
realEndDate: {
type: Date,
default: ""
},
//not final version
riskRegister: [{
name: String,
wpId: {
type: mongoose.Types.ObjectId,
ref: 'projects.deliverables.workPackages.id',
required: true
},
probability: String,
impact: String,
riskOwner: String,
response: String,
duration: String,
trigger: String,
status: String,
plannedTimming: String
}],
deliverables: [{
body: String,
workPackages: [{
body: String,
activities: [{
body: String,
tasks: [{
content: String,
properties: [{
dependecies: Array,
risk: {
type: Number,
enum: [0,1],
required: true
},
estimatedTime: {
type: Number,
required: true
},
realTime: {
required: true,
default: 0,
type: Number
},
responsible: {
id: {
type: Number,
default: -1
},
type: {
type: String,
enum: [0, 1], //0 - user, 1 - team
default: -1
}
},
materialCosts: {
type: Number,
default: 0
},
status: {
type: Number,
default: 0
},
approval: {
type: Number,
default: 0
},
startDate: {
type: Date,
default: ""
},
finishDate: {
type: Date,
default: ""
},
endDate: {
type: Date,
default: ""
},
userStartDate: {
type: Date,
default: ""
},
endStartDate: {
type: Date,
default: ""
},
taskNum: {
type: Number,
required: true
},
lessonsLearn: {
insertedAt: {
type: Date,
default: Date.now
},
creatorId: {
type: mongoose.Types.ObjectId,
ref: 'users',
required: true
},
situation: {
type: String,
required: true
},
solution: {
type: String,
required: true
},
attachments: Array
}
}]
}]
}]
}]
}]
})
The only concern I would raise would be regarding deliverables. If in the future there is a use case to do some CRUD operation regarding activities or tasks on the workPackage, the mongodb position operator $ does not support inner arrays, so you would be forced to extract all the deliverables and in memory iterate over all and only after update the deliverables.
My sugestion would be to support only arrays in the first level on the object. The inner objects should be moduled in separate collection ( activities and tasks ). In latest versions of mongodb you now have support to transactions so you can implement ACID on your operations against database, so the manipulation of all this information can be done in an atomic way.

Mongoose: Join Operation, populate isn't possible

I'm currently struggling with a project of mine.
I've got a collection called "Games" and one "Participation".
When a user loggs in, he/she should be able to see the games and the individual participation status.
Therefore, I want to join these two collections but I can't use .populate() because I can't enter the neccessary Participation ID in the Games collection due to the fact, that I don't have the participation ID at the time I create a game. (So I would need to save the participation, remember the created ID and insert THIS id in the games collection afterwards)
The other way round would be a good solution (to populate Games in Participation) but initially, there are no participations in these collection, until a user clicks "Participate" or "Not Participate".
Basically I need a SQL query like that:
select * from games g, participation p where g.gamesId = p.gamesId AND p.username = [...]
Is there any possibility to achieve this?
Otherwise I would need to save every participation as a "Game", having the dependent username and his/her participation status in it.
Wouldn't prefer this solution at all.
Thanks in advance!
In case it helps:
Here are my two collections:
Game:
var gameSchema = mongoose.Schema(
{
isHome: { type: Boolean, required: true },
time: { type: String, required: true, max: 100 },
uzeit: { type: String, required: true, max: 100 },
clubId: { type: mongoose.Types.ObjectId, required: true },
enemy: { type: String, required: true, max: 100 },
place: { type: String, required: true, max: 100 },
(participation: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Teilnahme' }])
});
Participation:
var participationSchema = mongoose.Schema(
{
playerAvailable: { type: Boolean, required: true },
clubId: { type: mongoose.Types.ObjectId, required: true },
gameId: { type: mongoose.Types.ObjectId, required: true, ref: 'Game' },
memberName: { type: String, required: true },
}
);

Categories