I want to get items per category in node js. how to get it. Here is the example that i want
"status": true,
"total_results": 4,
"categories": [
{
"id": 2,
"name": "Category 1",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
},
{
"id": 4,
"name": "Category 2",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
}
]
}
Here is the code i write for getting above array result in nodejs
pool.query(`Select * FROM categories WHERE catalog_id = '${fields.catalog_id}'`, async (error, result, field) => {
if (error) { // if error
console.log(error);
return false;
}
var Catarr = result.map((item,index)=>item.id)
pool.query(`Select * FROM items WHERE category_id IN (${Catarr})`, async (error, menuItems, field) => {
if (error) { // if error
console.log(error);
return false;
}
var parsed_items = [];
await result.forEach((item,index)=>{
var items = menuItems.filter((p_item)=>p_item.category_id == item.id)
var obj = {
name: item.name,
id: item.id,
items
}
parsed_items.push(obj)
})
res.status(200).json({status:true,total_results:result.length,categories:parsed_items});
});
});
Sharing my suggestion as per my understanding; Please refer to below code snippet:
const data={ "status": true,
"total_results": 4,
"categories": [
{
"id": 2,
"name": "Category 1",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
},
{
"id": 4,
"name": "Category 2",
"items":[
{
"name" :"item1"
},
{
"name": "item2"
}
]
}
]
};
const expectedResult=data.categories.reduce((iter, item)=>{
iter[item.name]=item.items? item.items.length : 0; // we can use item.id if required
return iter;
}, {});
alert(JSON.stringify(expectedResult));
console.log('Items per category - ',expectedResult);
Related
![]:(https://i.stack.imgur.com/5IOEd.png)
![]:(https://i.stack.imgur.com/feAyS.png)
How do I write json code?
I need an example of writing batchUpdate json in google form api.
thank you.
********
const update = {
requests: [
{
createItem: {
item: {
title: "TEST ",
title: "TEST RADIO",
questionGroupItem: {
grid: {
columns: {
type: "RADIO",
options: [
{ value: "A"},
{ value: "B"},
{ value: "C"},
{ value: "D"},
]
}
}
}
},
location: { index: 1 },
},
}
]
};
const res = await forms.forms.batchUpdate({
formId: createResponse.data.formId,
requestBody: update,
});
********
When I saw your request body, I thought that there are 2 modification points.
There are 2 title properties like title: "TEST ", and title: "TEST RADIO",.
In your request body, it is required to include rowQuestion of questions.
When these points are reflected in your script, it becomes as follows.
Modified request body:
const update = {
"requests": [
{
"createItem": {
"item": {
"title": "TEST ",
"questionGroupItem": {
"grid": {
"columns": {
"type": "RADIO",
"options": [
{
"value": "A"
},
{
"value": "B"
},
{
"value": "C"
},
{
"value": "D"
}
]
}
},
"questions": [
{
"rowQuestion": {
"title": "smaple1"
}
},
{
"rowQuestion": {
"title": "sample2"
}
}
]
}
},
"location": {
"index": 1
}
}
}
]
};
In this sample modified request body, 4 columns and 2 rows are created.
References:
Method: forms.batchUpdate
CreateItemRequest
I want to update an array within a document, only if the object being pushed to the "items" array has a unique id within the "items" array.
{
"_id": "6039e37cb6b60f4694a16705",
"list_name": "Example Picklist",
"author_id": "6027f627141a75567cc2e0b0",
"author_name": "Test",
"items": [
{
"upcs": [
"111222333"
],
"qty": 10,
"id": "123456",
"name": "Item A"
},
{
"upcs": [
"444555666"
],
"qty": 22,
"name": "Item B",
"id": "987654"
}
],
"status": "initialized",
"__v": 0
}
For example, I should be able to add:
{
"name": "Item C",
"qty": 99,
"upcs": ["111555999"],
"id": "111111"
}
but not:
{
"name": "Item C",
"qty": 99,
"upcs": ["111555999"],
"id": "123456"
}
My put request is currently not refusing req.bodys with already existing ids, after I tried implementing JohnnyHK's answer to this question.
router.put('/:id', auth, async (req, res) => {
const item = req.body; // insert above examples
try {
let picklist = await Picklist.findById(req.params.id);
if (!picklist)
return res.status(404).json({ json: 'Picklist not found' });
picklist = await Picklist.findByIdAndUpdate(
{ _id: req.params.id, 'items.id': { $ne: item.id } },
{
$push: { items: item },
},
{ new: true }
);
res.json(picklist);
} catch (err) {
console.error(err.message);
res.status(500).json({ msg: 'Server Error' });
}
});
What am I getting wrong? At the moment it will push anything that fits with the Schema, and doesn't stop ID duplicates.
The error is that I was using
Picklist.findByIdAndUpdate()
instead of
Picklist.findOneAndUpdate()
Following is the Sample Workspace document.I want to update box positions when we drag and drop at front end.
{
"_id": ObjectId("5eaa9b7c87e99ef2430a320b"),
"logo": {
"url": ".../../../assets/logo/dsdsds.png",
"name": "testUpload"
},
"name": "My World",
"sections": [{
"box": [{
"_id": ObjectId("5da87b33502d6c634b3aa7ce"),
"name": "Meran To",
"position": 0
},
{
"_id": ObjectId("5da87b33502d6c7d873aa7d0"),
"name": "Documentation",
"position": 2
},
{
"_id": ObjectId("5da87b33502d6cdbb93aa7cf"),
"name": "File Manager Upload File Drive",
"position": 1
},
{
"_id": ObjectId("5da87b33502d6c276a3aa7cd"),
"name": "File Manager Upload File Drive",
"position": 1
}
],
"id": 1,
"title": "Simplicity",
"description": "Follow your barriers"
},
{
"box": [],
"id": 2,
"title": "xfxdfxcx 34",
"description": "sdsdsd sfsfsd ewrewrewre"
}
]
}
I send the updated positions from front-end to back-end via API, in an array as shown below.
[
{
"id": "5da87b33502d6c634b3aa7ce",
"position": 0
}, {
"id": "5da87b33502d6c7d873aa7d0",
"position": 1
}, {
"id": "5da87b33502d6cdbb93aa7cf",
"position": 2
}, {
"id": "5da87b33502d6c276a3aa7cd",
"position": 3
}]
I am currently updating DB using the below code
for (const el of req.body) {
await this.model.updateOne({
_id: req.params.workspaceId,
sections: {
$elemMatch: {
id: req.params.sectionId
}
},
'sections.box': {
$elemMatch: {
_id: el.id
}
},
}, {
$set: {
'sections.$[outer].box.$[inner].position': el.position
}
}, {
arrayFilters: [{
'outer.id': req.params.sectionId
}, {
'inner._id': el.id
}],
upsert: false,
});
}
But this is not the best method, it hits DB multiple times.
so I need to optimize this code with mongoose query itself.
May be using $set / $push.I don't know any exact methods.
So basically we need to remove the external for loop and make it work with mongoose itself.This is my requirement.
Thanks in advance for all the support.
There are 2 methods for doing it.
bulkWrite
const bulkOps = [];
req.body.forEach((el) => {
const upsertDoc = {
updateOne: {
filter: {
_id: req.params.workspaceId,
sections: {
$elemMatch: {
id: req.params.sectionId
}
},
'sections.box': {
$elemMatch: {
_id: el.id
}
},
},
update: {
$set: {
'sections.$[outer].box.$[inner].position': el.position
}
},
arrayFilters: [{
'outer.id': req.params.sectionId
}, {
'inner._id': el.id
}],
upsert: false,
}
};
bulkOps.push(upsertDoc);
});
const result = await this.model.collection.bulkWrite(bulkOps);
bulkUpdate
const bulkUpdate = this.model.collection.initializeUnorderedBulkOp();
req.body.forEach((el) => {
bulkUpdate.find({
_id: req.params.workspaceId,
sections: { $elemMatch: { id: req.params.sectionId } },
'sections.box': { $elemMatch: { _id: el.id } },
}).arrayFilters([{ 'outer.id': req.params.sectionId }, { 'inner._id': el.id }])
.updateOne({ $set: { 'sections.$[outer].box.$[inner].position': el.position }
});
});
await bulkUpdate.execute();
I have an array of schools like this:
{
"schools": [
{
"name": "S1",
"id": 1
},
{
"name": "S2",
"id": 2
},
{
"name": "S3",
"id": 3
}
]
}
and each school has schedule. To Get that I iterate the schools array in a promise and when I get the response I get an array like this
{
"schools": [
{
"name": "S1",
"id": 1
},
{
"name": "S2",
"id": 2
},
{
"name": "S3",
"id": 3
}
],
"schedules": [
[],
[
{
"id_schedule": 58,
"hour1": "13:00:00",
"hour2": "20:00:00",
"id_schools_schedule": 2
}
],
[
{
"id_schedule": 59,
"hour1": "06:30:00",
"hour2": "22:30:00",
"id_schools_schedule": 3
}
]
]
}
I want to know. how to asign the response of each item?
this is my code
for (var i =0; i < datosRes.schools.length; i++){
array_horarios.push(ObtSchedule(datosRes.schools, i))
}
Promise.all(array_horarios).then(response => {
datosRes.horarios = response;
eq.local = data;
}).catch(err => {
return res.json(200,{"datos":datosRes});
})
function ObtHorario(schools, i){
return new Promise(function(resolve, reject){
var id_school = schools[i].id;
Mod_Schedule.obtSchedule(id_school,function(error, data){
if(error || data.error){
errorDB = {"error_log": error, "error_data": data.error};
reject(errorDB)
}else{
resolve(data)
}
})
})
}
What I am doing wrong?
I get the response but only I want to add to each item of schools the schedules
Thanks in advance
First thing first:
You can send ONE response to ONE request. So your question to send multiple responses is invalid.
Here's what you can do, you can get the array of schools with their schedules.
If you are using MongoDB, here's what you can do:
Using Aggregate query:
db.schools.aggregate([
{
$match: {} // Your condition to match schools here
},
{
$lookup: {
from:"schedules",
localField: id,
foreignField: id_schools_schedule,
as: "schedulesData"
}
},
]);
Here, you will get data something like:
[
{
"name": "S1",
"id": 1,
"schedulesData": []
},
{
"name": "S2",
"id": 2,
"schedulesData": [{
"id_schedule": 58,
"hour1": "13:00:00",
"hour2": "20:00:00",
"id_schools_schedule": 2
}]
},
{
"name": "S3",
"id": 3,
"schedulesData": [
{
"id_schedule": 59,
"hour1": "06:30:00",
"hour2": "22:30:00",
"id_schools_schedule": 3
}
]
}
]
I'm trying to get a map reduce operation to work using Nodejs, mongoose and MongoDB.
I've got a fairly flat schema structure and I want to get a list of value/date pairs per 'named' object. There is clearly something wrong with the map reduce function but I can't see how to fix it to get the format I'm after.
The MongoDB document schema is as follows:
{ "name" : "object1", "value" : "123", "date" : "2013-01-02 01:00:00" }
{ "name" : "object1", "value" : "456", "date" : "2013-01-02 02:00:00" }
{ "name" : "object2", "value" : "123", "date" : "2013-01-02 02:00:00" }
The map reduce functions I'm using in my Mongoose Schema are as follows:
var o = {};
o.map = function () {
emit(
{ 'name': this.name },
{'data': [ { 'value': this.value, 'date': this.date} ] }
)
}
o.reduce = function (k, vals) {
var reduced = {'data': []};
for (var i in vals) {
reduced.data.push(vals[i]);
}
return reduced;
}
this.mapReduce(o, function(err, model) {
if(err) console.log(err);
model.find().exec(cb);
});
What I'd like to see is some JSON along the lines of
[
{
"name": "object1",
"data": [
{
"value": "123",
"date": "2013-01-02T01:00:00.123456"
},
{
"value": "456",
"date": "2013-01-02T02:00:00.123456"
},
]
},
{
"name": "object2",
"data": [
{
"value": "123",
"date": "2013-04-22T13:10:03.893018"
},
...
]
},
...
But I end up getting this nested mess! Can someone give me a pointer on what I've missed!!
[
{
"_id": {
"name": "object1"
},
"value": {
"data": [
{
"data": [
{
"data": [
{
"data": [
{
"value": "123",
"date": "2013-01-02T02:00:00.123456"
}
]
},
{
"data": [
{
"value": "465",
"date": "2013-01-02T01:00:00.123456"
}
]
},
... etc
try something like that: (not tested but the idea is here I think :))
var o = {};
o.map = function () {
emit(this.name, { 'value': this.value, 'date': this.date} )
}
o.reduce = function (k, vals) {
var reduced = {name: k, data : []};
for (var i in vals) {
reduced.data.push(vals[i]);
}
return reduced;
// or just return vals? it's already the array you want.
}