Mongodb, nodejs: find an object and update its value - node.js

I am struggling to find a solution to update client's data to the database.
I have a document looking like this:
{
"_id": {
"$oid": "60249fccf992b73b340c7c94"
},
"username": "john",
"inv": {
"id01": {
"n": "Apple",
"r": "0"
},
"id02": {
"n": "Pear",
"r": "0"
},
"id03": {
"n": "Pear",
"r": "0"
},
"id04": {
"n": "GreenApple",
"r": "0"
}
}
}
and this is the json data sent from the client
{
"id02": {
"n": "Pear",
"r": "1",
"z": "-1.0001",
"x": "-2.34",
"y": "-2.41"
},
"id03": {
"n": "Pear",
"r": "1",
"z": "-1.0002",
"x": "-0.52",
"y": "-2.41"
}
}
I want to look for the objects from the json data sent by client in the database (for instance: "id02") and update its value. I am pretty new to Mongodb so I am struggling with finding the proper technique to do so.
The document should be looking like this
{
"_id": {
"$oid": "60249fccf992b73b340c7c94"
},
"username": "john",
"inv": {
"id01": {
"n": "Apple",
"r": "0"
},
"id02": {
"n": "Pear",
"r": "1",
"z": "-1.0001",
"x": "-2.34",
"y": "-2.41"
},
"id03": {
"n": "Pear",
"r": "1",
"z": "-1.0002",
"x": "-0.52",
"y": "-2.41"
},
"id04": {
"n": "GreenApple",
"r": "0"
}
}
}
I try this but it replaces everything in the "inv" with the new data
var addToSet = {};
for(var key in data)
{
addToSet[key] = data[key];
}
db.get().collection('userdata').updateOne({ username: ws.userId},{'$set': {'inv':addToSet}})

I use this :
const Product = require(Path Model Moongose);
const data = {
NameProducts: req.body.title,
TitleProducts: req.body.body,
PriceProducts: req.body.price,
TagesProducts: req.body.tags
};
await Product.updateOne({ _id: Find with your idea }, { $set: data });

Related

How to get the Header Row from XLSX Sheet-JS Node module (React)?

I dont understand why the fields of the first row NOT offered in the response?
Ive used this file: file. And Getting the following JSON response upon reading it:
{
"opts": {
...
},
"SheetNames": [
"Dates"
],
"Sheets": {
"Dates": {
"!margins": {
...
},
"A1": {
"v": "Name",
"t": "s",
"w": "Name"
},
"B1": {
"v": "Birthday",
"t": "s",
"w": "Birthday"
},
"A2": {
"v": "George Washington",
"t": "s",
"w": "George Washington"
},
"B2": {
"v": "1732-02-22",
"t": "s",
"w": "1732-02-22"
},
"A3": {
"v": "John Adams",
"t": "s",
"w": "John Adams"
},
"B3": {
"v": "1735-10-19",
"t": "s",
"w": "1735-10-19"
},
"A4": {
"v": "Thomas Jefferson",
"t": "s",
"w": "Thomas Jefferson"
},
"B4": {
"v": "1743-04-13",
"t": "s",
"w": "1743-04-13"
},
"!ref": "A1:B4"
}
},
"Preamble": {},
"Strings": [
...
],
"SSF": {
...
},
"Metadata": {
...
},
"Workbook": {
...
},
"Custprops": {
...
},
"Props": {
...
}
And I created this parsing algorithm:
const getFirstColumnsFromSheet = () => {
const selectedSheetName = "Dates";
return (
selectedSheetName &&
Object.entries(wb['Sheets'][selectedSheetName])
.filter(
(it) => it[0] === it[0].toUpperCase() && /[A-Z]+[1]$/.test(it[0])
)
.map((it) => (it[1] as any)['v'])
);
};
It works fine but its a little try hard, I wonder if there is a simple way to get the column that doesnt include FILTERING - using the uppercase check and if it has the format of "Some letter and the number 1" characters - from ALL the data. (This simply filters out so you only get the fields like :A1,B2,C1,D1 etc...
Is there a more simple solution to this?

MongoDB dynamically conditional filtering

I am trying to create a form builder and generator and from generated forms, I will collect answers. After collecting answers I want to filter them according to some filter parameters and get average results for each category.
Questions have categories(attributeGroupOne&Two) bind to them.
I have the following structure for my answers.
{
"form": [{
"_id": {
"$oid": "62295d028b6b895048b7da96"
},
"questionType": "lickert5",
"label": "deneme sorusu 1",
"attributeGroupTwo": "deneme kategorisi alt 2",
"attributeGroupOne": "deneme kategorisi",
"name": "Question_1",
"weight": 4,
"type": "radio",
"options": {
"1": "Çok Az",
"2": "Az",
"3": "Bazen",
"4": "Genellikle",
"5": "Her Zaman"
}
}, {
"_id": {
"$oid": "62295d028b6b895048b7da95"
},
"questionType": "lickert10",
"label": "deneme sorusu 2",
"attributeGroupTwo": "deneme alt 3",
"attributeGroupOne": "deneme kategorisi",
"name": "Question_2",
"weight": 4,
"type": "radio",
"options": {
"1": "1",
"2": "2",
"3": "3",
"4": "4",
"5": "5",
"6": "6",
"7": "7",
"8": "8",
"9": "9",
"10": "10"
}
}, {
"_id": {
"$oid": "62295d028b6b895048b7da94"
},
"questionType": "trueFalse",
"label": "deneme sorusu 3",
"attributeGroupTwo": "deneme alt 5",
"attributeGroupOne": "deneme kategorisi",
"name": "Question_3",
"weight": 4,
"type": "radio",
"options": {
"0": "Yanlış",
"10": "Doğru"
}
}, {
"_id": {
"$oid": "62295d028b6b895048b7da93"
},
"questionType": "lickert5",
"label": "deneme sorusu 4",
"attributeGroupTwo": "deneme main sub",
"attributeGroupOne": "deneme main 2",
"name": "Question_4",
"weight": 4,
"type": "radio",
"options": {
"1": "Çok Az",
"2": "Az",
"3": "Bazen",
"4": "Genellikle",
"5": "Her Zaman"
}
}],
"surveyName": "deneme formu",
"createdBy": {
"$oid": "61becc2c230fc12274683b6a"
},
"createdAt": {
"$date": "2022-03-10T02:05:54.039Z"
},
"updatedAt": {
"$date": "2022-03-10T02:05:54.039Z"
},
"__v": 0
}
https://i.stack.imgur.com/xT2Cq.png
Without additional filter just by filtering category with following query I am getting reports that I wanted.
.aggregate([
{ $unwind: '$answers' },
{
$group: {
_id: '$answers.SubCategory',
CalculatedWeight: { $avg: '$answers.CalculatedWeight' },
formId: { $first: formId }
}
},
{ $project: { _id: 1, CalculatedWeight: 1, formId: 1 } },
{ $out: 'results' }
])
results:
{
"CalculatedWeight": 19.35483870967742,
"formId": {
"$oid": "62295d028b6b895048b7da92"
}
}
https://i.stack.imgur.com/HxqBe.png
I successfully added age filtering with following block
const docs = await model
.aggregate([
{
$match: {
$and: [
{ age: { $gt: minAge, $lt: maxAge } },
{ formId: { $eq: formId } }
]
}
},
{ $unwind: '$answers' },
{
$group: {
_id: '$answers.SubCategory',
CalculatedWeight: { $avg: '$answers.CalculatedWeight' },
formId: { $first: formId }
}
},
{ $project: { _id: 1, CalculatedWeight: 1, formId: 1 } },
{ $out: 'results' }
])
But I have 5 filters that are, gender, department, age, working years, and education level. If possible I want to be able to combine them with dynamic querying but I don't want to write 120 if cases for combining them. I can't think a way to programmatically filter and calculate according to filters.
Thank you in advance. The question itself might be unclear, sorry about it. I can elaborate if you point out where it is lacking.
Edit:
Filter types can be seen below. Age and working years will be a period with min and max values. If possible I want to be able to combine all filter types but it will probably statistically unreasonable due to the small pool of entries ~200. Most common combinations for filters are: Gender-Department-Age, Working Years- Department, Education - Gender.
Filters:
gender: String - enum
department: String - enum
age: Number - Min and Max
working years: Number - Min and Max
education: String - enum
For anyone else struggling with the same thing, I figured it out this way.
In my situation since only the match query is subject to change I constructed match queries according to query parameters I am getting with following code.
var array = Object.entries(req.query)
array.forEach(x => {
var z = { [x[0]]: { $eq: x[1] } }
matchTry.$and.push(z)
})
output:
{
"$and": [
{
"department": {
"$eq": "IT"
}
},
{
"gender": {
"$eq": "male"
}
}
]
}
Then use mongoose with it
const docs = await model
.aggregate()
.match(match)
.exec()
res.status(200).json({ data: docs })

Scan for a nested Map inside a List that don't exist

I would like some help with structuring a scan via AWS CLI to get results where the "on_demand" map does not exist. The "on_demand" map is nested in other parent maps [0 , 1, 2...]. Which in turn are in the playlist List.
The conditions for the scan would be where is_offsite = true, video_type = OFFSITE and of course the troublesome condition where the "on_demand" map does not exist.
This is my table structure.
{
"Items": [
{
"playlist": {
"L": [
{
"M": {
"duration": {
"N": "46"
},
"on_demand": {
"M": {
"bucket": {
"S": "s3 Bucket"
},
"key": {
"S": "bucket url to video file"
}
}
},
"download": {
"M": {
"bucket": {
"S": "s3 bucket"
},
"key": {
"S": "bucket url to video file"
}
}
},
"status": {
"S": "on_demand"
}
},
"M": {
"duration": {
"N": "60"
},
"on_demand": {
"M": {
"bucket": {
"S": "s3 Bucket"
},
"key": {
"S": "bucket url to video file"
}
}
},
"download": {
"M": {
"bucket": {
"S": "s3 bucket"
},
"key": {
"S": "bucket url to video file"
}
}
},
"status": {
"S": "on_demand"
}
}
}
]
},
"video_type": {
"S": "OFFSITE"
},
"id": {
"S": "random hash id"
},
"is_offsite": {
"BOOL": true
},
}
]
}
Any assistance will be much appreciated.
This was accomplished by using the following:
aws dynamodb scan \
--table-name table-name \
--projection-expression "id" \
--filter-expression 'is_offsite = :os AND video_type = :vt AND attribute_not_exists(playlist[0].on_demand)' \
--expression-attribute-values '{":os": { "BOOL": true},":vt": {"S": "OFFSITE"}}'

How to delete a element from LIST in dynamoDB

I have an atrribute with LIST data type be like:
"ketban": {
"L": [
{
"S": "01012018000007"
},
{
"S": "01012018000009"
},
{
"S": "01012018000006"
},
{
"S": "01012018000005"
}
]
}
Now i want to delete a item and result be like:
"ketban": {
"L": [
{
"S": "01012018000007"
},
{
"S": "01012018000009"
},
{
"S": "01012018000006"
}
]
}
I can do it with SET data type but not with LIST data type.
Please help me!!

How to iterate through an object that was passed from a database via ejs on the client

My last question was marked as a duplicate which is understandable because I didn't explain it enough so now i'll explain it in more depth.
Here is my node.js server code, i'm using ejs as my template engine and mongo.js to connect to my mongo database
server.get('/test', (req,res) => {
db.surveys.find((err,survey) => {
res.render('test',{
survey:survey
});
});
});
The object in my database that is being passed to my view is
[{
"surveyCode": 123456,
"1": {
"question": "What is your name?",
"1": {
"type": "text",
"placeholder": "Enter your name",
"header": ""
}
},
"2": {
"question": "What grade are you in?",
"1": {
"type": "radio",
"content": "9th"
},
"2": {
"type": "radio",
"content": "10th"
},
"3": {
"type": "radio",
"content": "11th"
},
"4": {
"type": "radio",
"content": "12th"
}
},
"3": {
"question": "What is your gender?",
"1": {
"type": "radio",
"content": "Male"
},
"2": {
"type": "radio",
"content": "Female"
},
"3": {
"type": "radio",
"content": "Other"
}
}
}]
I've tried everything to try to iterate through the object, for Each and for loops didn't work for me. How can I iterate though the object in my view so I can separate each object and store it in a variable. Keep in mind it's an object in an object in an object, and I've tried to do a loop in a loop in a loop.
Thank You!
Here is some code showing how to access the inner members of your object:
var a = [
{
"1":{
"1":{
"type":"text",
"placeholder":"Enter your name",
"header":""
},
"question":"What is your name?"
},
"2":{
"1":{
"type":"radio",
"content":"9th"
},
"2":{
"type":"radio",
"content":"10th"
},
"3":{
"type":"radio",
"content":"11th"
},
"4":{
"type":"radio",
"content":"12th"
},
"question":"What grade are you in?"
},
"3":{
"1":{
"type":"radio",
"content":"Male"
},
"2":{
"type":"radio",
"content":"Female"
},
"3":{
"type":"radio",
"content":"Other"
},
"question":"What is your gender?"
},
"surveyCode":123456
}
];
for(var idx=0; idx < a.length; idx++) {
var b = a[idx];
for(var bkey in b) {
var c = b[bkey];
for(var ckey in c) {
var d = c[ckey];
for(var dkey in d) {
if (typeof d === 'object') {
console.log(dkey);
console.log(d[dkey]);
}
}
}
}
}

Resources