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();
Related
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
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
}
},
],
});
My mongoose(5.5.15) query is sometimes able to "findById" the document and "select" the sub-document based on the conditional query provided. However, just one second later (or whatever amount of time) the exact same request fails to return anything back. Nothing is changing on the MongoDb document so it has to be something I am doing wrong.
I have already used the console.log(nextDeliveryDate) to get the date object output when the query seemingly fails and the output of the log seems to be the same (except for the time difference from the previous of course). So the error appears to be completely random and uncontrolled.
const today = new Date();
let nextDeliveryDate = new Date();
nextDeliveryDate.setHours(0);
nextDeliveryDate.setMinutes(0);
nextDeliveryDate.setSeconds(0);
if (today.getDay() < 2) {
nextDeliveryDate.setDate(today.getDate() + (2 - today.getDay()));
} else {
nextDeliveryDate.setDate(today.getDate() + (7 - today.getDay()));
}
const result = await Kitchen.findById(req.query.kitchen).select({
deliveries: {
"$elemMatch": {
delivery_date: {
$gte: nextDeliveryDate
}
}
}
}).exec();
// SCHEMA from a different file
const kitchenSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
_created: Date,
_lastModified: {
type: Date,
default: Date.now
},
name: {
type: String,
required: true,
unique: true
},
location: {
street: String,
unit: String,
city: String,
state: String,
zipcode: Number,
latitude: Number,
longitude: Number
},
routes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Routes'
}],
manager: {
type: String
},
employees: [{
type: String
}],
deliveries: [{
_id: mongoose.Schema.Types.ObjectId,
_created: Date,
weekday: Number,
delivery_date: Date,
routes: [{...}],
status: {
type: String,
default: 'preparing'
}
}]
});
So sometimes I get the perfect result that I am expecting (the correct delivery object from the array) and sometimes it just doesn't find anything. Please help. Thanks.
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 },
}
);
I'm trying to accomplish something really easy but still manage to fail.
What I am trying to do is when I get a get request on my server I want to return all documents BUT just the specific fields populated.
My schema goes as follows
var clientSchema = new Schema({
name:{
type: String,
required: true
},
phone:{
type: String,
required: true
},
email:{
type: String,
required: true
},
address: {
type: String,
required: false
}
});
var orderDetailsSchema = new Schema({
//isn't added to frontend
confirmed:{
type: Boolean,
required: true,
default: false
},
service:{
type: String,
required: true
},
delivery:{
type: String,
required: false
},
payment:{
type: String,
required: false
},
status:{
type: String,
required: true,
default: "new order"
},
});
var orderSchema = new Schema({
reference:{
type: String,
required: true
},
orderdetails: orderDetailsSchema,
client: clientSchema,
wheelspec: [wheelSchema],
invoice:{
type: Schema.Types.ObjectId,
ref: 'Invoice'
}
});
What I want is to return only client.phone and client.email plus orderdetails.status but still retain reference field if possible
I have tried using lean() and populate() but had no luck with them. Is there anything utterly simple I am missing? Or what I am trying to achieve is not that easy?
Thanks!
You can specify the fields to return like this:
Order.findOne({'_id' : id})
.select('client.phone client.email orderdetails.status reference')
.exec(function(err, order) {
//
});
Alternative syntax
Order.findOne({'_id' : id})
.select('client.phone client.email orderdetails.status reference')
.exec(function(err, order) {
//
});
I've made a number of assumptions here, but you should be able to see the idea.
Simply do like this :-
Order is model name which is registered in mongoose.
Order.findById(id) // set id you have to get
. populate('client')
.select('client.phone client.email orderdetails.status reference')
.exec(function(err, order) {
//
});
You can use projection.
await Order.findById(diaryId, {phone: 1, email: 1, status: 1})
If phone:1 is set to 1, it is included, if phone:0, then it's excluded.