i have a MONGODB database to places like Restaurant Or Cafe and each place have an Array Of Object with name TABLES and each object has Number of table, and Array of booking Dates and details user can book any table by date and time so i want to check available tables and return the table that not booked in this time that user wants to book..
HERE IS MY SCHEMA FOR TABLES ARRAY
tables: [
{
num: Number,
isBooked: {
type: Boolean,
default: false,
},
bookings: [
{
User: {
type: mongoose.Schema.Types.ObjectId,
ref: "Users",
},
Name: {
type: String,
},
Date: {
type: String,
},
Time: {
type: String,
},
Note: {
type: String,
},
numOfPersons: {
type: Number,
},
},
],
},
],
and if user want to book a table at 20/8/2021 , 4:00PM we should check available table for this user at this time requested, we should check on tables and return available table the we push the booking information into it..
i tried some query but always return the whole place not just available table..
const stringDate = new Date(date).toLocaleDateString();
const placeId = req.body.placeId;
const availableTable = await Places.findOne({
_id: placeId,
"tables[0].bookings": {
$not: {
$elemMatch: { $and: [{ Date: stringDate }, { Time: time }] },
},
},
});
availableTable.isBooked = true;
availableTable.bookings.push({
Name: name,
Time: time,
Date: stringDate,
numOfPersons: parseInt(personsNumber),
Note: note,
User: userId,
});
await availableTable.save()
First of all, for simplicity, you should have a separate collection for tables with the restaurant/cafe id in it. That way you can easily do CRUD operations on tables and it would the best approach to handle it.
Related
I know that this can be a repeat question but none of the existing answers solved my problem.
I have a friendsSchema like below:
const friendsSchema = new mongoose.Schema({
owner: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Player'
},
friends: [{
friendId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Player'
},
isFromFacebook: {
type: Boolean,
default: false
},
thisFriendReceivedGiftTimeStamp: {
type: Date,
default: null
},
thisFriendSentGiftTimeStamp: {
type: Date,
default: null
}
}]
}, {
timestamps: true
});
The client is sending me an array of friendsIds.
So, I want to find all objects in friends array which matches all friendsIds and update their thisFriendReceivedGiftTimeStamp to Date.now().
Consider the client is sending 100s of ids in friendsIds array, what will be the most efficient way to achieve the result.
Thanks in advance.
db.collection.update({IF YOU WANT TO ADD QUERY ACCORDING TO OWNER FIELD PLEASE ADD HERE},
{
"$set": {
"friends.$[x].thisFriendReceivedGiftTimeStamp": new Date()
}
},
{
"arrayFilters": [
{
"x.friendId": {
$in: [
1,
3,
5
]
}
}
],
"multi": true
})
arrayFilters should work great here. But I am not 100% sure about efficiency
Here is a working mongoplayground link
I want to Query and array with regex inside and mongoose (mongoDB) model.
I want to search inside the nested array of the Productmodel :
const productSchema = new schema(
{
name: requiredString,
sku: requiredUniqueNumber,
ean: requiredUniqueNumber,
suppliers: [{ type: mongoose.Schema.Types.ObjectId, ref: SupplierModel }],
categories: [{ type: mongoose.Schema.Types.ObjectId, ref: CategoryModel }],
mainImage: requiredString,
images: [{ type: String }],
description: requiredString,
stock: requiredNumber,
price: requiredNumber,
totalOrders: requiredNumber,
reviews: [review],
},
{
timestamps: true,
count: true,
}
);
The model inside the "suppliers" array is:
const supplierSchema = new schema(
{
supplierName: requiredUniqueString,
invoiceAddress: address,
visitAddress: address,
status: supplierStatusEnum,
contacts: address,
accountType: accountTypeEnum,
logo: requiredString,
user: { type: schema.Types.ObjectId, ref: "products" },
},
{
timestamps: true,
}
);
Now here's the problem, if i query and and populate() i get all the results. But for some reason I cannot search inside the Array containing several suppliers. Here's of what i have:
foundProducts = await ProductModel.find({
$or: [
{
name: {
$regex: regex,
},
},
{
"suppliers.supplierName": {
$regex: regex,
},
},
{
description: {
$regex: regex,
},
},
],
});
The object in JSON:
If he finds that the suppliers model contains the regex he should give back the whole porductmodel containing that supplier.
What is the best way to search in all the items inside of an nested array.
ps. I'm a junior developer comming from PostgreSQL, so bare with me while I'm trying this noSQL "thing" :)
I was doing the wrong query. I need to do
{
"suppliers._id": {
$regex: regex,
},
},
I can only search on _id, since this is the way that i "modeled" it.
I want to populate a date range picker display with highlighted cells where data exists in my database. I thus need to reduce my collection to an array of dates where records exist e.g.
// collection
[{
timestamp: ISODate("2020-01-28T20:42:00.000Z"),
data: 1,
},{
timestamp: ISODate("2020-01-28T18:42:00.000Z"),
data: 10,
},{
timestamp: ISODate("2020-01-28T15:42:00.000Z"),
data: 100,
},{
timestamp: ISODate("2020-01-25T15:42:00.000Z"),
data: 1000,
},{
timestamp: ISODate("2020-01-17T15:42:00.000Z"),
data: 10000,
}]
reduces to:
['2020-01-28', '2020-01-25', '2020-01-17']
The nature of the data stored in my database means that if any data exists on a given date, lots of data exists on that date. It is therefore slow to query the entire collection for a given date range and then reduce the result.
Is there a fast(er) way to query a collection to return the distinct set of dates on which data exists?
As I know you can only get json format result from mongodb query.
I could get the following result, which can be easily converted to the string array in javascript code:
[
{
"_id": "20200125"
},
{
"_id": "20200117"
},
{
"_id": "20200128"
}
]
I used $dateToString aggregation operator inside $project stage.
db.collection.aggregate([
{
$project: {
_id: 0,
date: {
$dateToString: {
format: "%Y%m%d",
date: "$timestamp"
}
}
}
},
{
$group: {
_id: "$date"
}
}
])
Playground
I have a NodeJS application where I use the mongoose library to communicate with my mongo database.
The application is about a game, where multiple rounds are played. And after each round, the results of the round are submitted! I want the values (a json) to be push to players.rounds. I have an _id and a players.id to determine where to push.
This is what I thought would be the right way (and I'm still a newbie in mongoose). It prints me no error, but the db document is not affected. Still zero items in players.rounds.
This is what I thought would be the right way (and I'm still a newbie in mongoose).
My mongoose schema:
const gameSchema = new mongoose.Schema(
{
categories: [
{ type: String }
],
countdown: Number,
players: [{
_id: false,
id: String,
rounds: [
{ type: Map, of: String }
],
score: { type: Number, default: 0 },
ready: { type: Boolean, default: false }
}]
}
);
The place where I'm executing:
Game.findOneAndUpdate(
{ _id: gameId, 'players.id': client.id },
{ $push: { 'players.$.rounds': values } }, function(err) {
if (err) {
console.log('ERROR when submitting round');
console.log(err);
}
});
It prints me no error, but the db document is not affected. Still zero items in players.rounds.
you need to change your schema Object. we need to specify {strict: false} for changing the inserted documents in mongoose.
const gameSchema = new mongoose.Schema(
{
categories: [
{ type: String }
],
countdown: Number,
players: [{
_id: false,
id: String,
rounds: [
{ type: Map, of: String }
],
score: { type: Number, default: 0 },
ready: { type: Boolean, default: false }
}]
}, {strict:false} );
I have the following schema in mongoose.
var AttendanceSchema = new mongoose.Schema({
ownerId: mongoose.Schema.Types.ObjectId,
companyId: mongoose.Schema.Types.ObjectId,
months: [
{
currentSalary: {
type: Number,
default: 0
},
month: {
type: Date,
},
salary: {
type: Number,
default: 0
}
days: [
{
manuallyUpdated: {
type: Boolean,
default: false
},
date: {
type: Date,
},
perDaySalary: {
type: Number,
default: 0
},
status: {
type: String,
}
}
]
}
]
});
I want to extract the the single object in days array.
Note: There is days array nested in months array and i have used $pull to pull out that day but i want to pull and push again (updated day).
i think you can do this if you know at which element inside days array there is information you need because days array will consist of multiple elements.
suppose that you need it from 1st element inside array:
Attendance.findOne({_id: request.id}, function(err, foundAttendance){
console.log(foundAttendance.days[0].date);
}
and you can change 0 to any number you want according to data you need.