Nodejs can't update index in an array in mongoDB [duplicate] - javascript

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
I'm trying to make an api for a bus ticketing sistem, but I can't seem to get an how to make it work in nodejs
[
{
"id":1,
"hour" : "7:30am"
, "seats" : [
0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0 ,0, 0
]
},
{
"id":2,
"hour" : "9:00am",
"seats" : [
0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0, 0 ,
0, 0, 0 ,0, 0
]
}
This is my mongodb query
db.schedules.update({"id":2}, {"$set" : {"seats.8" : "1"}});
and everything seems to work just fine until I try it on nodejs
router.put('/reserve/:id/:seat', function(req, res, next) {
schedules.update({"id": req.params.id}, { "$set":{ "seats." + req.params.seat+: "1"}}, function(err, doc) {
if (err) {
console.log(err);
return res.status(400).json({"error"});
}
if (doc.result.nModified) {
res.status(200).json({"status": "ok"});
} else {
res.status(400).json({"error": "The seat hasn't been reserved"});
}
});
this is the error returned:
SyntaxError: Unexpected token +
I have tried multiple ways and can't get that working

You have invalid javascript syntax here: schedules.update({"id": req.params.id}, { "$set":{ "seats." + req.params.seat+: "1"}} Can't concat a string in an object definition.
Try like this, using a property reference notation (that will create the property):
let updateObj = { $set: {} }
updateObject.$set['seats.' + req.params.seat] = '1'
schedules.update({"id": req.params.id}, updateObj, function ... )

Related

Data extract from and object issue javascript

I have json data like
[ [ RowDataPacket { content_id: 52 } ],
OkPacket {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0 } ]
How I get content_id part from this data set?
I got this data while calling a Stored Procedure using TypeORM.
here is the code I tried
const contentData = await connection.getRepository(Content).query('CALL getInitialContent()');
To be a valid JS object literal, your data would have to look like this:
[
[ { RowDataPacket: { content_id: 52 } } ],
{ OkPacket: { fieldCount: 0, affectedRows: 0, insertId: 0, serverStatus: 2, warningCount: 0, message: '', protocol41: true, changedRows: 0}
}
];
Once you have that, then getting the content_id field is reasonably trivial as long as you can comprehend the data structure - it's inside the first element of an array, which itself is an array. The first element of that inner array is an object. That then contains another object inside the "RowDataPacket" object, and and the content_id data you want is a property of that second object.
Shorthand version:
let data = [
[{
RowDataPacket: {
content_id: 52
}
}],
{
OkPacket: {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
}
];
let id = data[0][0].RowDataPacket.content_id;
console.log(id);
Longhand (so you can see the traversal of the data hierarchy step by step):
let data = [
[{
RowDataPacket: {
content_id: 52
}
}],
{
OkPacket: {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
}
];
let arr = data[0]; //get inner array
let obj = arr[0]; //get object inside the array
let packetObj = obj.RowDataPacket; //get object in the RowDataPacket property
let id = packetObj.content_id; //get the target data
console.log(id);

How to get specific keys from object? (JS)

I have this object:
728394 : {
"playersAmount" : 2,
"players" : {
"LRFe9w9MQ6hf1urjAAAB" : {
"nickname" : "spieler1",
"type" : "player1"
},
"nKUDWEd5p_FCBO4sAAAD" : {
"nickname" : "spieler2",
"type" : "player2"
},
"ghdaWSWUdg27sf4sAAAC" : {
"nickname" : "spieler3",
"type" : "spectator"
}
},
"activePlayer" : "LRFe9w9MQ6hf1urjAAAB",
"board" : [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]
]
}
How do I get everything of the object above except for the k/v pair "board"? is there any other way than just adding every key except the right one?
You can create a copy and then delete the unwanted key:
const copy = { ...original }
delete copy.unwantedProperty
Of course you can instead delete the property on the original if you don't care about mutating it.
(Note: if your environment doesn't support the syntax { ...original }, you can use Object.assign({}, original) instead.)
EDIT: Actually, this answer is even neater.
const { board, ...everythingButBoard } = yourObject
simple answer will be:
const copyObject = Object.assign({}, yourObject) // to make a copy of original variable
delete copyObject['keyToRemove'] // OR delete copyObject.keyToRemove
else if you want to delete from original variable:
delete yourObject['keyToRemove'] // OR delete yourObject.keyToRemove
I think you can create a new object excluding this key using a for...in
object = {
wantedKey: 'wantedValue',
wantedKey2: 'wantedValue2',
wantedKey3: 'wantedValue3',
unwantedKey: 'unwantedValue'
}
const newObject = {}
for (const key in object) {
if (key !== 'unwantedKey') newObject[key] = object[key]
}
console.log(newObject)
for more info about for...in: click here

Remove first element/array of an array in JavaScript

I have a problem with removing the first element of an array.
To be short, this is how my array looks like if I show it in console:
(11) [Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4)]
0 : (4) ["2017-09-20T16:00:00-07:00", 188.125, 0, 1]
1 : (4) ["2017-09-20T17:00:00-07:00", 123.125, 0, 1]
2 : (4) ["2017-09-20T18:00:00-07:00", 114.25, 0, 1]
3 : (4) ["2017-09-20T19:00:00-07:00", 115, 0, 1]
4 : (4) ["2017-09-20T20:00:00-07:00", 113.25, 0, 1]
5 : (4) ["2017-09-20T21:00:00-07:00", 115.625, 0, 1]
6 : (4) ["2017-09-20T22:00:00-07:00", 114.75, 0, 1]
7 : (4) ["2017-09-20T23:00:00-07:00", 114, 0, 1]
8 : (4) ["2017-09-21T00:00:00-07:00", 112.625, 0, 1]
9 : (4) ["2017-09-21T01:00:00-07:00", 108.375, 0, 1]
10 : (4) ["2017-09-21T02:00:00-07:00", 111.125, 0, 1]
length : 11
__proto__ : Array(0)
I want to remove the first one, 0, I tried using .shift() but didn't work.
Like my array is called myArray.data and I tried myArray.data.shift() and I get this error message:
TypeError: Cannot read property '0' of undefined
at bundle.js:1554
at Function._.map._.collect (vendor.js:11761)
at renderChart (bundle.js:1547)
at bundle.js:1611
at Scope.$digest (vendor.js:34716)
at Scope.$apply (vendor.js:34986)
at bundle.js:259
at vendor.js:14387
at _fulfilled (vendor.js:13992)
at self.promiseDispatch.done (vendor.js:14021)
Any ideas how to solve this?
Later edit:
The code is inside a chart generation function, this is the whole snippet:
data: {
type: chartType,
columns: [
['x'].concat(_.map(myArray.data, function (dataPoint) {
const x = (myArray.data).shift();
console.log(myArray.data);
console.log(x);
return moment(dataPoint[0]).valueOf();
})),
['Expected'].concat(_.map(myArray.data, function (dataPoint) {
return dataPoint[1];
})),
['Actual'].concat(_.map(myArray.data, function (dataPoint) {
return dataPoint[1];
}))
],
x: 'x'
},
I can reproduce the result wanted using Array.shift()
let arr = [
["2017-09-20T16:00:00-07:00", 188.125, 0, 1],
["2017-09-20T17:00:00-07:00", 123.125, 0, 1],
["2017-09-20T18:00:00-07:00", 114.25, 0, 1],
["2017-09-20T19:00:00-07:00", 115, 0, 1],
["2017-09-20T20:00:00-07:00", 113.25, 0, 1],
["2017-09-20T21:00:00-07:00", 115.625, 0, 1],
["2017-09-20T22:00:00-07:00", 114.75, 0, 1],
["2017-09-20T23:00:00-07:00", 114, 0, 1],
["2017-09-21T00:00:00-07:00", 112.625, 0, 1],
["2017-09-21T01:00:00-07:00", 108.375, 0, 1],
["2017-09-21T02:00:00-07:00", 111.125, 0, 1]
];
console.log(arr[0]);
arr.shift();
console.log(arr[0]);
.shift() is working fine.
Problem is in your Array which is going to shift, Check whether myArray.data consists of data, Error says you are trying to shift a value from a undefined (null) object.
splice(0,1) also working fine
You can remove the first array item usingz myArray.data.splice(0, 1) but the error tells that you are trying to apply array method to undefined value. Perhaps the $scope has not received the value yet

Javascript Array Difference with Different Initialization Method

Can someone explain to me why the following happens in Javascript Console (Node 7.2.0):
Array in example I has different behavior than example II and III
EXAMPLE I
> var x = new Array(3).fill(new Array(2).fill(0))
> x
[ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> x[0][0] = 1;
> x
[ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ] ]
EXAMPLE II
> var y = [...new Array(3)].map(()=>{return [...new Array(2)].map(()=>0)})
> y
> [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> y[0][0] = 1
> [ [ 1, 0 ], [ 0, 0 ], [ 0, 0 ] ]
EXAMPLE III
> var y = []
> y.push([ 0, 0 ])
> y.push([ 0, 0 ])
> y.push([ 0, 0 ])
> y
> [ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> y[0][0] = 1
> [ [ 1, 0 ], [ 0, 0 ], [ 0, 0 ] ]
It seems that different ways to initialize array will cause different behaviors of an array. I'm confused and thank you in advance.
array.fill() returns the modified array, so you're filling an array with multiple references to the same array. That is why when you modify it in one place, it automatically shows up in the other places.
The first example is equivalent to doing something like:
var arr = [ 0, 0 ];
var x = [ arr, arr, arr ];
The reason for the difference is that in JS, objects (including arrays) are not copied, they are linked. In example I, you fill the array with a single array.
> var x = new Array(3).fill(new Array(2).fill(0))
// You have filled x with three links to the same array
> x
[ [ 0, 0 ], [ 0, 0 ], [ 0, 0 ] ]
> x[0][0] = 1;
// You have now modified the actual array, this change is reflected in all the links to it.
> x
[ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ] ]
What you are doing is the same as doing:
var a = [ 0, 0 ]
var x = [ a, a, a ]
OR
var a = [ 0, 0 ]
var x = []
x.push(a)
x.push(a)
x.push(a)
BTW, using new Array() is generally a bad practice. There is no benefit over the array literal syntax. Also, using new Array(n) makes "empty slots" in your array, which is very odd and can cause problems in your programs if you don't fill all the slots.

Can't print a value in JS object

I'm trying to print a value stored in a JS object but I don't know how can I access it. Here's my code:
var the_votes = {
"Heredia": {
voters: 70000,
parties: {
pln: 0,
pac: 0,
plib: 0,
rc: 0
}
},
"San Jose": {
voters: 200000,
parties: {
pln: 0,
pac: 0,
plib: 0,
rc: 0
}
},
"Alajuela": {
voters: 80000,
parties: {
pln: 0,
pac: 0,
plib: 0,
rc: 0
}
},
"Cartago": {
voters: 50000,
parties: {
pln: 0,
pac: 0,
plib: 0,
rc: 0
}
},
"Puntarenas": {
voters: 100000,
parties: {
pln: 0,
pac: 0,
plib: 0,
rc: 0
}
},
"Limon": {
voters: 60000,
parties: {
pln: 0,
pac: 0,
plib: 0,
rc: 0
}
},
"Guanacaste": {
voters: 90000,
parties: {
pln: 0,
pac: 0,
plib: 0,
rc: 0
}
}
};
And I want to print the value "voters" on the console with this method:
function updateTable(votes) {
table_clear();
var table = $("#elections");
var tbody = table.append($("<tbody/>"));
$.each(votes, function (province, data) {
var row = $("<tr/>");
row.append($("<td/>")).html(province);
$.each(data.parties, function (partyName, partyValue) {
var td = $("<td/>");
td.html(partyValue);
row.append(td);
td = $("<td/>");
td.html();
console.log(province.voters);
row.append(td);
});
tbody.append(row);
});
};
I keep getting an "undefined" on this line: "console.log(province.voters);
How can I access the value under this method structure?
province is a string. It doesn't have a property voters.
data is the object you want to access (which you already do correctly for data.parties):
console.log(data.voters);
you want to console.log(data.voters);
province is simply the string identifier such as "Puntarenas"
alternatively you could do console.log(votes[province].voters);
To print voters for every province:
console.log(data.voters);
console.log(the_votes.Heredia.voters)
This will print voters in "Heredia"

Categories

Resources