update item of array of array in mongodb - arrays

I want to push an item to the array of items (root document > categories > subcategories > items)
I am using NodeJS with MongoDB npm package
My document structure should be like the following
{
"_id": "572a77641b24ed3404f43690"
"categories": [
{
"id": "572bbac072d7ee3026a69467"
"Name": "Foods",
"subcategories": [
{
"id": "572a777c1b24ed3404f43691",
"Name": "Pizza"
"items": [
{
"id": "572ba1666ca263303121acd4"
"Name": "4 Seasons",
"Price": "6.0"
}
]
}
]
}
]
}
My current code is
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { "categories.0.subcategories.$.items": item } }, function(err, result) {
res.send(result);
});
});
What can I do ?

Just found a solution, not clean one though but works properly !
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.findOne({ "categories.subcategories.id": ObjectId(subId) }, { "categories.subcategories.$": 1 }, function(err, doc) {
for (var i = 0; i < doc.categories[0].subcategories.length; i++) {
var elem = doc.categories[0].subcategories[i];
if (elem.id == subId) {
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { ["categories." + i + ".subcategories.$.items"]: item } }, function(err, result) {
res.send(result);
});
break;
}
}
});
});

Related

How to delete all sub array

In my MongoDB database, I have a collection 'produits' with documents like this
{
"_id": {
"$oid": "6048e97b4a5f000096007505"
},
"modeles": [
{
"id": "OppoA3",
"pieces": [
{
"id": "OppoA3avn"
},
{
"id": "OppoA3bat"
}]
]
},
{
"id": "OppoA1",
"pieces": [
{
"id": "OppoA1avn",
},
{
"id": "OppoA1batt",
}
]
}
]
}
How can I delete all modeles.pieces from all my documents.
I managed to delete with a filter on modeles.id but with that code but not on all the collection
db.produits.update(
{marque_id:'OPPO', 'modeles.id':'RENOZ'},
{$set:
{
'modeles.$.pieces': []
}
}
, { multi : true }
)
I would like all documents like this finally
{
"_id": {
"$oid": "6048e97b4a5f000096007505"
},
"modeles": [
{
"id": "OppoA3",
"pieces": []
},
{
"id": "OppoA1",
"pieces": []
}
]
}
Thank you for your help.
I have done a javascript loop like this, but i think it's not best practice
async removePieces(){
var doc
try {
doc = await produitModel.find()
for (var produit of doc) {
for (var modele of produit.modeles) {
const filter = {'marque_id': produit.marque_id, 'modeles.id': modele.id}
const set = {
$set: {
'modeles.$.pieces': []
}
}
await db.collection('produits').updateOne(filter, set)
}
}
console.log('removePieces() ==> Terminé')
} catch(err) {
console.log(err)
}
}
db.produits.update({
modeles: {//This is because your second document will create failure otherwise
$exists: true
}
},
{
$set: {
"modeles.$.pieces": []
}
},
{
multi: true
})

Push nested json values to array using node js

I need to show my json results into nested array format:
{
"state": [
{
"stateName": "tamilnadu"
}
],
"city": [
{
"cityName": "chennai"
}
]
}
This is my code. I'm new in node development
exports.stateId = function (req, res) {
state.find(req.body.countryId, function() {
var query = N1qlQuery.fromString('SELECT stateId,stateName FROM travel _type='state'');
myBucket.query(query, async function(err, result) {
var state=[];
await result.forEach(ele => {
var item= {
stateName:ele.stateName
}
if(ele.stateName != undefined)
state.push(item);
});
res.send({state});
});
});
};
exports.cityId = function (req, res) {
city.find(req.body.stateId, function() {
var query = N1qlQuery.fromString('SELECT cityId,cityName FROM travel where _type="city"');
myCluster.query(query, async function(err, result) {
var city=[];
await result.forEach(ele => {
var item= {
cityName:ele.cityName
}
if(ele.cityName != undefined)
city.push(item);
});
res.send({city});
});
});
};
Currently i will get results like two different array. i need to merge json results into single nested data
If you have the following data:
const data_1 =
{
"state": [
{ "stateName": "tamilnadu" }
]
};
const data_2 =
{
"city": [
{ "cityName": "chennai" } ]
};
and your desired object is:
{
"state": [
{
"stateName": "tamilnadu"
}
],
"city": [
{
"cityName": "chennai"
}
]
}
then you can use Object.assign method:
let desired = Object.assign({}, data_1, data_2);
console.log(`desired: `, desired)

Response duplicated but the count shows as 1

Using Dynamoose ORM with Serverless. I have a scenario where I'm finding user information based on recommendation.
The response is as follows
{
"data": {
"results": [
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
},
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
}
],
"count": 1
},
"statusCode": 200
}
Not sure where I'm going wrong as the items in the response seems to be duplicated but the count is 1.
Here is the code
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (recommendations.count == 0) {
return;
}
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
const response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);
});
};
EDIT: My previous code ignored the fact that your "Insider" query is asynchronous. This new code handles that and matches your edit.
const async = require('async'); // install async with 'npm install --save async'
[...]
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (_err) {
console.log(_err);
return callback(_err);
}
if (recommendations.count == 0) {
const response = {
data: {
results: [],
count: 0
},
statusCode: 200
};
return callback(null, response);
}
let results = [];
async.each(recommendations, (recommendation, cb) => { // We need to handle each recommendation asynchronously...
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => { // because this is asynchronous
if (_err) {
console.log(_err);
return callback(_err);
}
if (insider.count == 0) {
return cb(null);
}
recommendation.insiderInfo = insider;
results.push(recommendation);
return cb(null);
});
}, (err) => { // Once all items are handled, this is called
if (err) {
console.log(err);
return callback(err);
}
const response = { // We prepare our response
data: {
results: results, // Results may be in a different order than in the initial `recommendations` array
count: results.count
},
statusCode: 200
};
callback(null, response); // We call our main callback only once
});
});
};
Initial (partly incorrect) answer, for reference.
You are pushing the result of your mapping into the object that you are currently mapping and callback is called more than once here. That's a pretty good amount of unexpected behavior material.
Try the following:
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
let response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);

Get data from complex Json structure using NodeJs

json Structure:
{
"id" : "1",
"Data" : [
{
"name" : "abc",
},
{
"name" : "option1",
"position" : [
{
"name" : "option1",
"status" : [
{
"code" : "0",
"value" : "OFF"
},
{
"code" : "1",
"value" : "ON"
}
]
}]
} ]
}
Here,I want to get the data from above complex Json structure.How to do that,
Have tried below code but giving error like;
error: uncaughtException: Cannot read property 'status' of undefined
function myfunc(req,res){
var collectionname = db.collection("col1");
collectionname.find({}).each(function(err, doc) {
if(doc != null)
{
var fdata = [];
for(var i =0;i<doc.Data.length;i++){
fdata.push(doc.Data[i].position.status);
}
console.log("fdata............",fdata);
}
});
}
Please help with the same.
You can use foreach for prevent length undefined.
function myfunc(req,res)
{
let collectionname = db.collection("col1");
collectionname.find({}).each(function(err, doc)
{
if(doc != null)
{
let fdata = [];
for(let i in doc.Data)
{
for(let j in doc.Data[i].position)
{
fdata.push(doc.Data[i].position[j].status);
}
}
console.log("fdata............", fdata);
}
});
}
#MikaelLennholm have right, for(let i in doc.Data) works but not recommanded, be careful not to use it in prototyped or object-built arrays.
EDIT:
function myfunc(req,res)
{
db.collection('col1').find({}).each(function(err, doc)
{
if(err)
{
console.log('[INFOS] Request fail, more details:\n', err);
}
else if(doc)
{
let fdata = [];
if(doc.Data && doc.Data.length)
{
for(let i = doc.Data.length-1; i >= 0; i--)
{
if(doc.Data[i].position && doc.Data[i].position.length)
{
for(let j = doc.Data[i].position.length-1; j >= 0; j--)
{
if(doc.Data[i].position[j].status)
{
fdata = fdata.concat(doc.Data[i].position[j].status);
}
}
}
}
}
console.log("[INFOS] Datas:\n", fdata);
}
});
}
im a newbie at nodejs, hope this's correctly
//I assume this is a object or you can convert from string to object
var data = {
"id": "1",
"Data": [
{
"name": "option1",
"position": [
{
"name": "option1",
"status": [
{
"code": "0",
"value": "OFF"
},
{
"code": "1",
"value": "ON"
}
]
}]
}]
}
var statusArr = data.Data[0].position[0].status;
console.log(...statusArr);
Result: { code: '0', value: 'OFF' } { code: '1', value: 'ON' }
Parse through position array as well
function myfunc(req,res){
var collectionname = db.collection("col1");
collectionname.find({}).each(function(err, doc) {
if(doc != null)
{
var fdata = [];
for(var i =0;i<doc.Data.length;i++){
for(var j =0;j<doc.Data[i].position.length;j++){
fdata.push(doc.Data[i].position[j].status);
}
}
console.log("fdata............",fdata);
}
});
}

Parse Objects and Arrays in Json data in AngularJs

I am trying to build an array of objects using the data I get from backend service using angularjs. Here is how I get the data
"mylist": [
{
"name": "Test1",
"moreInfo": {
"moreInfoText": "More test",
},
"companyInfo": {
"companyNameInfo": "ABC",
"url": "http://www.google.com",
}
},
{
"name": "Test2",
"moreInfo": {
"moreInfoText": "More test2",
},
"companyInfo": {
"companyNameInfo": "ABC2",
"url": "http://www.yahoo.com",
}
},
]
I want to parse it so I can combine it all in one array of objects like
[{"name": "Test1", "moreInfoText": "More test","companyNameInfo": "ABC", "url": "http://www.google.com"},{ "name": "Test2", "moreInfoText": "More test2","companyNameInfo": "ABC2", "url": ""}]
Try this:
var flatten = function(object) {
var newObj = {};
for (var key in object) {
var item = object[key];
if (typeof item !== 'object') {
newObj[key] = item;
}
else {
var flattened = flatten(item);
for (var k in flattened) {
newObj[k] = flattened[k];
}
}
}
return newObj;
};
var newList = [];
myList.forEach(function(object) {
newList.push(flatten(object);
});
console.log(newList) //this should be what you want

Resources