I want to subtract already booked data from totalSpots variable whenever this condition returns true
if(totalSpots > bookings.count()){
return true
}
return false
And when it return true I want to store it into a variable called filteredData.
GET route to fetch parking availability:
exports.getParkingListByCriteria = async (req, res) => {
try {
endTime = getEndTime(req.body.startTime, req.body.duration);
let parkings = await Parking.find(
{
"location.city": req.body.city,
}
);
let parkingList = [];
let parkingIds = [];
parkings.forEach((parking) => {
isParkingAvailable(parking.availability, req.body.startTime, endTime);
{
parkingList.push(parking);
parkingIds.push(parking._id);
}
});
const bookings = await Booking.find({
"isBookingCancelled.value": false,
parkingId: { $in: parkingIds },
});
let groupBookings = {};
let tmppid = "";
bookings.forEach((booking) => {
tmppid = booking.parkingId.toString();
if (typeof groupBookings[tmppid] === "undefined")
groupBookings[tmppid] = [];
groupBookings[tmppid].push(booking);
});
var keys = Object.keys(groupBookings);
console.log("parkingList -> ", parkingList);
parkingList.filter((booking) => {
isParkingSlotAvailable(groupBookings, Object.keys(groupBookings));
}); //Stuck in the function
res.status(200).send(parkingList);
} catch (error) {
return res.status(500).json({ error: error.message });
}
};
isParkingSlotAvailable Function:
exports.isParkingSlotAvailable = (groupBookings, keys) => {
groupBookings.forEach((booking) => {});
};
The sample data from console.log(parkingList)
parkingList -> [
{
contactInfo: { name: 'Claudia Shields', phoneNumber: 8904672101 },
location: {
address: '737 applegate court',
city: 'bowie',
state: 'rhode island',
country: 'greece',
zipCode: 10825
},
coordinates: { lng: 34.048954, lat: 10.299556 },
_id: new ObjectId("62d12053cb03235286511d54"),
merchantId: new ObjectId("62c950dfc96c2b690028be88"),
price: 16,
parkingType: 'residence',
parkingInfo: [ [Object] ],
totalSpots: [ 127 ],
status: 'active',
isFeePaid: false,
parkingZone: [],
availability: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
specialEvents: [],
createdAt: 2022-07-15T08:07:47.997Z,
updatedAt: 2022-07-15T09:29:58.696Z,
__v: 0
},
]
The sample data from console.log(groupBookings)
groupBookings: {
'62d12053cb03235286511d54': [
{
duration: [Object],
isBookingCancelled: [Object],
_id: new ObjectId("62d2a9d1cf93195bef1923af"),
parkingId: new ObjectId("62d12053cb03235286511d54"),
user: new ObjectId("62c95116c96c2b690028be8e"),
date: 2022-07-22T00:00:00.000Z,
startTime: 2022-07-22T05:30:00.000Z,
endTime: 2022-07-22T08:40:00.000Z,
isFeePaid: false,
status: 'sent',
isStarted: false,
isEnabled: false,
createdAt: 2022-07-16T12:06:42.002Z,
updatedAt: 2022-07-16T12:15:08.578Z,
__v: 0
},
{
duration: [Object],
isBookingCancelled: [Object],
_id: new ObjectId("62d553f80e8fa13f1295514c"),
parkingId: new ObjectId("62d12053cb03235286511d54"),
user: new ObjectId("62c95136c96c2b690028be9a"),
date: 2022-07-22T00:00:00.000Z,
startTime: 2022-07-22T10:30:00.000Z,
endTime: 2022-07-22T12:30:00.000Z,
isFeePaid: false,
status: 'sent',
isStarted: false,
isEnabled: false,
createdAt: 2022-07-18T12:37:12.682Z,
updatedAt: 2022-07-18T12:37:12.682Z,
__v: 0
}
]
}
Try to change your filter function like this.
Also, make sure that you update the parkingList since filter does not edit the array in-place.
parkingList = parkingList.filter((booking) => {
const booked = groupBookings[booking._id];
const alreadyBooked = booked ? booked.length : 0;
return booking.totalSpots[0] > alreadyBooked;
});
Related
In node.js I am getting only partial data back.In the second object some data are missing.
The response:
{
'62d12069cb03235286511d5e': [
{
duration: [Object],
isBookingCancelled: [Object],
_id: new ObjectId("62d55611f4a5817f6b0441c6"),
parkingId: new ObjectId("62d12069cb03235286511d5e"),
user: new ObjectId("62c9511cc96c2b690028be91"),
date: 2022-07-22T00:00:00.000Z,
startTime: 2022-07-22T06:30:00.000Z,
endTime: 2022-07-22T08:30:00.000Z,
isFeePaid: false,
status: 'sent',
isStarted: false,
isEnabled: false,
createdAt: 2022-07-18T12:46:09.040Z,
updatedAt: 2022-07-18T12:46:09.040Z,
__v: 0
},
{
duration: [Object],
isEnabled: false,
createdAt: 2022-07-18T12:49:49.921Z,
updatedAt: 2022-07-18T12:49:49.921Z,
__v: 0
}
]
}
Sometime it gives full data but sometime it retrieves only partial data like above. Here is the query.
const bookings = await Booking.find({
"isBookingCancelled.value": false,
// parkingId: { $in: parkingIds },
});
let groupBookings = {};
let tmppid = "";
bookings.forEach((booking) => {
tmppid = booking.parkingId.toString();
if (typeof groupBookings[tmppid] === "undefined")
groupBookings[tmppid] = [];
groupBookings[tmppid].push(booking);
});
console.log(groupBookings);
Booking schema;
ParkingId: ref: Parking, user: referenced to auth, date, startTime, duration: {days, hours, minutes}, endTime, isBookingcancelled, isFeePaid, isSatrted, isEnabled, paymentId refernced to Payment, and status
const {category, parent} = newCategory;
const newCat = new Category({
_id: new mongoose.Types.ObjectId(),
name: category,
parent: parent
}).save((err, res) => {
if(err) { console.log(err)}
else{
console.log("res in create category:", res);
// io.to(user.room).emit('create-category-to-list', {res});
}
})
In log
res in create category: {
codewords: [],
children: [],
_id: 604916cf866a154e284b2e29,
name: 'nameofasdasdasdcat',
parent: 60490c9ce00e8b7a38cf4752,
path: '60490c9ce00e8b7a38cf4752#604916cf866a154e284b2e29',
_v:0
}
Here the document is created but not assigned to its parent why this is happening.
Here you can see parent children array is empty
root: {
children: [],
_id: 60490c9ce00e8b7a38cf4752,
name: 'root',
path: '60490c9ce00e8b7a38cf4752',
_v:0
}
Here i am using mongoose pulgin(mongoose-mpath) for create a tree form data.
For mongoose-mpath https://www.npmjs.com/package/mongoose-mpath
In getChildrenTree function need to pass options as lean:false
const parent = await Folder.findOne({ _id: user.rootId });
const tree = await parent.getChildrenTree(
{
populate: 'codewords',
options: { lean: false } //you need to pass options as lean: false
});
console.log({ tree });
In log
{
tree: [
{
codewords: [],
children: [],
_id: 604c6c5bc8a2e03ee43c4c7b,
name: 'Category-name-2',
parent: 604c690b87924705a401f9ce,
path: '604c690b87924705a401f9ce#604c6c5bc8a2e03ee43c4c7b',
__v: 0
},
{
codewords: [],
children: [],
_id: 604c6ce2c8a2e03ee43c4c7d,
name: 'Category-name-2',
parent: 604c690b87924705a401f9ce,
path: '604c690b87924705a401f9ce#604c6ce2c8a2e03ee43c4c7d',
__v: 0
},
{
codewords: [],
children: [Array],
_id: 604c6d21c8a2e03ee43c4c7e,
name: 'Category-name-3',
parent: 604c690b87924705a401f9ce,
path: '604c690b87924705a401f9ce#604c6d21c8a2e03ee43c4c7e',
__v: 0
}
]
}
for your better understanding you can check mongoose-mpath github issue section ==>
https://github.com/vikpe/mongoose-mpath/issues/10
Why and how am I saving only document from find query when I pass 3 ids?
I wanted to get from that loop what will return
router.post("/addBand", async (req, res) => {
let singers = req.body.singer
let singerArr = singers.split(', ')
let singer
for (let i = 0; i < singerArr.length; i++) {
// solo = await GroupBand.findOne({ singer: ObjectId(singerArr[i]) }).populate('singer')
singer = await Singer.find({ _id: ObjectId(singerArr[i]) })
console.log(1, singer);
}
console.log(2, singer);
const addedGroup = new GroupBand({
bandName: req.body.bandName,
singer: singer, // [...singer],
debutDate: Date.parse(req.body.debutDate)
})
console.log(3, addedGroup);
return
But it seems like the only one get is from the last id I request. I also tried the spread operator incase it might need to just spread its value, but I get singer is not iterable
1 [ { createdAt: 2019-11-16T05:43:43.971Z,
updatedAt: null,
deletedAt: null,
assignedAt: null,
_id: 5dcf8c8fef739a6159938ca8,
name: 'KyuHyun',
__v: 0 } ]
1 [ { createdAt: 2019-11-16T05:48:51.194Z,
updatedAt: null,
deletedAt: null,
assignedAt: null,
_id: 5dcf8dc320742961c8b5a801,
name: 'Yesung',
__v: 0 } ]
1 [ { createdAt: 2019-11-16T05:53:14.469Z,
updatedAt: null,
deletedAt: null,
assignedAt: null,
_id: 5dcf8eca20742961c8b5a808,
name: 'Ryewook',
__v: 0 } ]
2 { createdAt: 2019-11-16T05:53:14.469Z,
updatedAt: null,
deletedAt: null,
assignedAt: null,
_id: 5dcf8eca20742961c8b5a808,
name: 'Ryewook',
__v: 0 }
3 { createdAt: null,
updatedAt: null,
deletedAt: null,
assignedAt: null,
_id: 5dda2fb9e69e6c22d429bbd9,
bandName: 'Super Junior - K.R.Y',
singer:
[ { createdAt: 2019-11-16T05:53:14.469Z,
updatedAt: null,
deletedAt: null,
assignedAt: null,
_id: 5dcf8eca20742961c8b5a808,
name: 'Ryewook',
__v: 0 } ],
debutDate: 2006-11-04T16:00:00.000Z }
Try this
let singerArr = singers.split(', ')
let singerArrayId=singerArr.map(ele=>ObjectId(ele)) or // let singerArrayId=singerArr.map(ele=>mongoose.Types.ObjectId(ele))
let data=await Singer.find({'_id': { $in:singerArrayId }});
After I got the result from split I loop them to pass on Singer document and find their ids
You should use the &in operator to retrieve more than one documents from your db.
There is an example of use here
EDIT
Try this without the for loop :
singer = await Singer.find({ _id : $in: singerArr }})
This should do the trick as $in operator take an array of ids as argument.
This is code i have used, fetched the all data in database, but i have not getting in value. I'm new for sequelize.
Project.findAll({ raw: true}).then(function (users) {
console.log(users);
console.log(users.dataValues);
}).catch(function (err) {
console.log('Oops! something went wrong, : ', err);
});
This is Output:
This is console.log(users);
[ DAO {
dataValues:
{ idProject: 1,
projectName: 'Symfony',
isActive: '1',
createdAt: 2018-10-23T06:32:43.000Z,
modifiedAt: 2018-10-23T06:32:43.000Z },
_previousDataValues:
{ idProject: 1,
projectName: 'Symfony',
isActive: '1',
createdAt: 2018-10-23T06:32:43.000Z,
modifiedAt: 2018-10-23T06:32:43.000Z },
options: { isNewRecord: false, isDirty: false, raw: true },
hasPrimaryKeys: true,
selectedValues:
RowDataPacket {
idProject: 1,
projectName: 'Symfony',
isActive: '1',
createdAt: 2018-10-23T06:32:43.000Z,
modifiedAt: 2018-10-23T06:32:43.000Z },
__eagerlyLoadedAssociations: [],
isNewRecord: false }.....
This is console.log(users.dataValues);
undefined
How is it possible?
When you use findAll, it returns an array, as you can see here in the documentation:
http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-findAll
so you should iterate over this array, like so:
Project.findAll({ raw: true})
.then(projects => {
projects.forEach(project => {
console.log(project);
console.log('project name', project.projectName);
})
}).catch(function (err) {
console.log('Oops! something went wrong: ', err);
});
Optionally you could use Async/Await for a cleaner code:
try {
const projects = await Project.findAll({ raw: true});
projects.forEach(project => {
console.log('project name ', project.projectName);
})
} catch(err) {
console.log('Oops! something went wrong: ', err);
}
When I want to create a new record in sails.js, I receive a logical error.
When I delete the following lines in my Controller, it's working:
amaliat_owner: req.param('amaliat_id') || 0,
place_die_owner: req.param('place_die_id') || 0,
media_place_die_owner: req.param('media_place_die_id') || 0,
media_owner: req.param('media_id') || null,
media_amaliat_owner: req.param('media_amaliat_id') || 0,
My route is:
'POST /delneveshte/create': 'DelneveshteController.create'
My model is:
module.exports = {
attributes: {
body: {
type: 'string',
columnType: 'text'
},
date_time: {
type: 'string',
},
is_confirmed: {
type: 'boolean',
defaultsTo: false
},
likee: {
type: 'number',
columnType: 'integer',
defaultsTo: 0
},
favorite: {
type: 'number',
columnType: 'integer',
defaultsTo: 0
},
user_owner: {
model: 'user',
},
shahid_owner: {
model: 'shahid',
},
amaliat_owner: {
model: 'amaliat',
},
media_place_die_owner: {
model: 'mediaplacedie',
},
place_die_owner: {
model: 'placedie',
},
media_owner: {
model: 'media',
},
media_amaliat_owner: {
model: 'mediaamaliat',
},
user_delneveshte_favorites: {
collection: 'userdelneveshtefavorite',
via: 'delneveshte_owner'
},
user_delneveshte_likes: {
collection: 'userdelneveshtelike',
via: 'delneveshte_owner'
},
},
};
My controller is:
create: async function (req, res, next) {
console.log(req.param('place_die_id'));
Delneveshte.create({
body: req.param('body'),
date_time: req.param('date_time'),
likee: req.param('like') || 0,
favorite: req.param('favorite') || 0,
is_confirmed: req.param('is_confirmed') || 0,
user_owner: req.param('user_id'),
shahid_owner: req.param('shahid_id') || 0,
amaliat_owner: req.param('amaliat_id') || 0,
place_die_owner: req.param('place_die_id') || 0,
media_place_die_owner: req.param('media_place_die_id') || 0,
media_owner: req.param('media_id') || null,
media_amaliat_owner: req.param('media_amaliat_id') || 0,
}, function (err, new_del) {
console.log("1");
if(err){
console.log("2");
return res.json({'status':false});
}
console.log("2");
return res.json({'status':true, 'result':new_del});
});
},
I use postman to send the request as follows:
But I receive the JSON {"status": false} and no record is created in the database. How can I fix my problem?
Some things to clarify:
Can you show the error? You can do that adding it to the json response.
If you put a defaultsTo property in the model, you shouldnt put it in the controller.
You have a lot of associations, so you can't send 0 as value of that associations because 0 is not a valid identifier. You should put a valid id or undefined.