I like to update an entry in mongodb. But lodash only update one value in the array. I send this object to my node.js server:
{ _id: 5593df7c087e59a00c04cda3,
name: 'blueberry',
uuid: 'b9407f30-f5f8-466e-aff9-25556b57fe6d',
major: '12345',
minor: '12345',
position: 'Kantine',
__v: 18,
messages:
[ { _id: 5593df7c087e59a00c04cda4,
timeRange: [Object],
url: '',
message: 'j',
title: 'jv',
messageType: 'text' },
{ _id: 5593df7c087e59a00c04cda4,
timeRange: [Object],
url: '',
message: 'j',
title: 'jv',
messageType: 'text' } ] }
Here is the code for the update of the mongodb-entry:
// Updates an existing ibeacons in the DB.
exports.update = function(req, res) {
Ibeacons.findById(req.params.id, function (err, ibeacons) {
if (err) { return handleError(res, err); }
if(!ibeacons) { return res.send(404); }
var updated = _.merge(ibeacons, req.body);
updated.save(function (err) {
if (err) { return handleError(res, err); }
return res.json(200, ibeacons);
});
});
};
But I get this as result:
{ _id: 5593df7c087e59a00c04cda3,
name: 'blueberry',
uuid: 'b9407f30-f5f8-466e-aff9-25556b57fe6d',
major: '12345',
minor: '12345',
position: 'Kantine',
__v: 18,
messages:
[ { _id: 5593df7c087e59a00c04cda4,
timeRange: [Object],
url: '',
message: 'j',
title: 'jv',
messageType: 'text' },
{ _id: 5593df7c087e59a00c04cda4,
timeRange: [Object],
url: '',
message: 'j',
title: 'jv',
messageType: 'text' } ] }
Maybe someone can help me.
Ok I get it. the version of lodash was on 2.4.1 now I updated it to 3.1.0 and it works. :D
Related
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;
});
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);
}
I am trying to get a query to run with both must and must_not, but have not had any luck with the syntax I am attempting. I see a lot of people on StackOverflow using quotes on both sides like they would be in a Curl call, but this is straight out of a node application.
I will show the query that does work, and I am simply trying to add what I do not want to be included in the outcome. In either case, because this is just trash data that is on a local dev environment, the outcome should match.
First the working query:
client.search({
index: config.ES_INDEX,
type: "issue",
body: {
query: {
match: {
issue_state: 'Closed'
}
},
size: 1000
}
}).then(function(resp){
console.log(util.inspect(resp, {showHidden: false, depth: null}));
}).catch(function(err){
console.log('Failed to search. ' + err.message);
});
Output:
{ took: 5,
timed_out: false,
_shards: { total: 5, successful: 5, failed: 0 },
hits:
{ total: 1,
max_score: 1,
hits:
[ { _index: 'noc_tool',
_type: 'issue',
_id: 'Sy2IQFMLe',
_score: 1,
_source:
{ job_name: 'Job Name 1',
is_maintenance: 'no',
servicenow_id: 'lkjjklh',
type: 'Chase',
start_time: '1970-01-01T23:15:00.000Z',
maint_reminder: null,
update_duration: '4 Hours',
location: 'Test Group',
issue_state: 'Closed',
notes: [ { created_on: 1484063571941, body: 'lkjlkjhlkj' } ],
emailService: { lastEmailAt: 1484237594114 },
created_on: 1484063571941,
updated_on: 1484240538801,
reason: 'because I want to' } } ] } }
Now, the failed query:
client.search({
index: config.ES_INDEX,
type: "issue",
body: {
query: {
bool: {
must: [
{
term: {
issue_state: 'Closed'
}
}
],
must_not: [
{
term: {
is_maintenance: 'yes'
}
}
]
}
},
size: 1000
}
}).then(function(resp){
console.log(util.inspect(resp, {showHidden: false, depth: null}));
}).catch(function(err){
console.log('Failed to search. ' + err.message);
});
Output:
{ took: 6,
timed_out: false,
_shards: { total: 5, successful: 5, failed: 0 },
hits: { total: 0, max_score: null, hits: [] } }
Any help here would be much appreciated.
I ended up using a little "reverse logic" but here is what is working..
return new Promise(function(resolve, reject) {
client.search({
index: config.ES_INDEX,
type: "issue",
body: {
query: {
bool: {
must:[
{
match: {
issue_state: 'Closed'
}
},
{
match: {
is_maintenance: 'no'
}
}
]
}
},
size: 1000
}
}).then(function (resp) {
resolve (resp.hits.hits);
}).catch(function (err) {
reject('Failed to search. ' + err.message);
});
I getting data from mongodb via mongoose. Then I try pass data to jade via res.render, but always get error TypeError: Cannot read property 'name' of null, but this property is exist and valid.
The code:
router.get('/item/:sku', (req, res, next) => {
Item.getItem(req.params.sku, (err, data) => {
console.log(data)
if(err)
next(err)
res.render('item', {
title: data.name,
data: data
})
})
})
Output:
{ sale: false,
createdAt: Fri Apr 29 2016 01:11:48 GMT+0700 (KRAT),
ordered: 0,
views: 0,
tags: [ 'tag1', 'tag2', 'tag3', 'tag4' ],
images: [ 'squirrel.jpg' ],
__v: 0,
backImage: '',
category: 57223f8ac80eb66928eae23e,
sku: 'SCH-002',
salePrice: 0,
price: 250,
description: 'test description',
name: 'Squirrel',
_id: 57225264b83ae185f3b2f4dc }
GET /item/SCH-002 200 1398.341 ms - 19177
/Users/lee/Projects/shepki/routes/index.js:30
title: data.name,
TypeError: Cannot read property 'name' of null
at /Users/lee/Projects/shepki/routes/index.js:30:18
at /Users/lee/Projects/shepki/modules/item.js:55:5
But if remove title and pass just whole data - its OK. I don't understand what's wrong.
Thanks.
I have a Node app (v0.8.26) running on Express (v3.4.8). In that app I have a route that sends an array of objects in the response body. What I'm finding is that doing so immediately begins spinning up the Node memory usage and before long everything shuts down. I'm getting a little desperate so I'm hoping someone can help (quickly).
Here's my route:
get_products: function(req, res) {
var san = req.params.san;
// Authenticate and then retrieve
client.login(datasources.api.auth.sourceId, datasources.api.auth.password, function(err, authToken) {
if (err) {
return res.send(401, err);
}
client.getProducts(token, san, function(err, products) {
if (err) {
var httpStatus = err.httpStatus || 500;
if (httpStatus === 500) {
console.trace(err);
}
return res.send(httpStatus, err.message);
}
if (products) {
return products.length > 0
? res.send(200, products) // <--- ERROR OCCURS HERE
: res.send(200, []);
}
else {
return res.send(403, 'Purchase is not allowed at this time.');
}
});
});
},
And the array being returned looks like this:
[ { PRODUCTID: '7',
PRODUCTNAME: 'Token 1',
QTY: '500',
PRICE: '5',
AVAILABLE: '1',
PRODUCTTYPE: '1',
BILLINGDEALNAME: 'Token 1' },
{ PRODUCTID: '8',
PRODUCTNAME: 'Token 2',
QTY: '1000',
PRICE: '9',
AVAILABLE: '1',
PRODUCTTYPE: '1',
BILLINGDEALNAME: 'Token 2' },
{ PRODUCTID: '9',
PRODUCTNAME: 'Token 3',
QTY: '2000',
PRICE: '16',
AVAILABLE: '1',
PRODUCTTYPE: '1',
BILLINGDEALNAME: 'Token 3' },
{ PRODUCTID: '5',
PRODUCTNAME: 'Token - Free',
QTY: '500',
PRICE: '0',
AVAILABLE: '0',
PRODUCTTYPE: '0',
BILLINGDEALNAME: 'Token - Free Token Use' },
{ PRODUCTID: '6',
PRODUCTNAME: 'Token - Prepaid',
QTY: '500',
PRICE: '0',
AVAILABLE: '0',
PRODUCTTYPE: '0',
BILLINGDEALNAME: 'Token - Prepaid Token Use' } ]
I know it's not a ton of information, but it's all I have. If I force the route to return an empty array in the response, there's no problem. I don't know where else to look.
Help?!
UPDATE
I've tweaked the code slightly for debugging. The ternary operator has been ditched:
if (products.length > 0) {
//return res.send(200, []);
console.error('RETURNING PRODUCTS');
console.error(products);
// return res.send(200, []);
return res.send(200, products);
}
else {
return res.send(200, []);
}
The key to this, for my specific problem, at least, was to downgrade Express.js from 3.4.x to 3.3.x. Because this is a production system, I wasn't able to play with it in order to gain a more sophisticated understanding of what was happening and I've never been able to reproduce this in my downstream environments.
Just wanted to close this out for anyone who may be searching later.
try recent version of nodejs - 0.10.26 - i have similiar issues in nodejs of 0.8.x versions
probably you can use streaming in response
if (products.length > 0) {
res.statusCode = 200;
products.map(res.write);
res.end();
}
else {
return res.send(200, []);
}