Print all mongoDB data to string nodejs - javascript

I have a sample mongo document like this:
> db.chat.find().pretty()
{
"_id": ObjectId("555f1c0c7f4b820758b439b0"),
"user": "Guest1",
"friend": [{
"userfriend": "Guest2",
"noidung": [{
"method": "send",
"date": "2015-05-22T19:11:34+07:00",
"content": "allloooo"
}, {
"method": "receive",
"date": "2015-05-23T09:08:14+07:00",
"content": "yes man"
}]
}, {
"userfriend": "Guest3",
"noidung": [{
"method": "send",
"date": "2015-05-23T15:42:34+07:00",
"content": "foo 15:42"
}, {
"method": "receive",
"date": "2015-05-23T15:42:45+07:00",
"content": "bar 15:43"
}]
}]
}
And in my server.js, i use this code to print all data:
var chathistory = db.collection('chat');
chathistory.find().toArray(function (err, docs) {
console.log(docs)
});
And i get this log in my terminal:
[ { _id: 555f1c0c7f4b820758b439b0,
user: 'Guest1',
friend: [ [Object], [Object] ] } ]
'friend' field doesn't print all, its only [Object], so how can i get full data.

To print all the data, use the JSON.stringify() method
db.collection('chat').find().toArray(function(err, docs) {
console.log(JSON.stringify(docs));
});

Related

How to update nested object in array (Mongoose/MongoDB)

I've been struggling to get my around how to update a object in a nested array with a particular id. I've attempted to implement $set as shown below. I want to be able to update the task with an _id of 62ff74bfe80b11ade2d34455 with the data from the request body.
{
"_id": "62fa5aa25778ec97bc6ee231",
"user": "62f0eb5ebebd0f236abcaf9d",
"name": "Marketing Plan",
"columns": [
{
"name": "todo",
"_id": "62fa5aa25778ec97bc6ee233",
"tasks": [
{ ====> here
"title": "Task Four",
"description": "This is task four",
"subtasks": [
{
"name": "wash dshes",
"completed": false,
"_id": "62ff74bfe80b11ade2d34456"
},
{
"name": "do homework",
"completed": false,
"_id": "62ff74bfe80b11ade2d34457"
}
],
"_id": "62ff74bfe80b11ade2d34455"
}
]
},
{
"name": "doing",
"_id": "62fa5aa25778ec97bc6ee234",
"tasks": []
},
{
"name": "done",
"_id": "62fa5aa25778ec97bc6ee235",
"tasks": []
}
],
"__v": 0
}
const updatedTask = await Board.findOneAndUpdate(
{
"columns.tasks._id": req.params.id,
},
{ $set: { "columns.$.tasks": req.body } },
{ new: true }
);
You can use the positional operator in combination with an arrayfilter. Here's an example how you'd update a specific field of the relevant task:
db.collection.update({
"columns.tasks._id": req.params.id
},
{
"$set": {
"columns.$[].tasks.$[t].title": "it works"
}
},
{
"arrayFilters": [
{
"t._id": req.params.id
}
]
})
You can also try this on mongoplayground.
If you're looking for a way to replace the matching task object itself you can do:
db.collection.update({
"columns.tasks._id": req.params.id
},
{
"$set": {
"columns.$[].tasks.$[t]": req.body
}
},
{
"arrayFilters": [
{
"t._id": req.params.id
}
]
})

AWS Lambda Athena getQueryResults With no results

I'm trying to get the output of getQueryResults using the below code:
var AWS = require('aws-sdk');
var athena = new AWS.Athena();
const DEBUG = process.env.DEBUG;
const GLOCA_ENVID = process.env.GLOCA_ENVID;
const GLOCA_AWS_ACCOUNTID = process.env.GLOCA_AWS_ACCOUNTID;
const GLOCA_AWS_REGION = process.env.GLOCA_AWS_REGION;
exports.handler = function(event, context, callback) {
athena.getQueryResults({
QueryExecutionId: "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
},function(err,data){
if (err) console.log(err);
else {
console.log("Body: ", data);
}
});
}
Below is the output:
{
UpdateCount: 0,
ResultSet: { Rows: [ [Object] ], ResultSetMetadata: { ColumnInfo: [Array] } }
}
The output should look something like this:
{
"ResultSet": {
"Rows": [
{
"Data": [
{
"VarCharValue": "date"
},
{
"VarCharValue": "location"
},
{
"VarCharValue": "browser"
},
{
"VarCharValue": "uri"
},
{
"VarCharValue": "status"
}
]
},
{
"Data": [
{
"VarCharValue": "2014-07-05"
},
{
"VarCharValue": "SFO4"
},
{
"VarCharValue": "Safari"
},
{
"VarCharValue": "/test-image-2.jpeg"
},
{
"VarCharValue": "200"
}
]
},
{
"Data": [
{
"VarCharValue": "2014-07-05"
},
{
"VarCharValue": "SFO4"
},
{
"VarCharValue": "IE"
},
{
"VarCharValue": "/test-image-2.jpeg"
},
{
"VarCharValue": "200"
}
]
}
],
"ResultSetMetadata": {
"ColumnInfo": [
{
"CatalogName": "hive",
"SchemaName": "",
"TableName": "",
"Name": "date",
"Label": "date",
"Type": "date",
"Precision": 0,
"Scale": 0,
"Nullable": "UNKNOWN",
"CaseSensitive": false
},
{
"CatalogName": "hive",
"SchemaName": "",
"TableName": "",
"Name": "location",
"Label": "location",
"Type": "varchar",
"Precision": 2147483647,
"Data": [
"Scale": 0,
"Nullable": "UNKNOWN",
"CaseSensitive": true
},
{
"CatalogName": "hive",
"SchemaName": "",
"TableName": "",
"Name": "browser",
"Label": "browser",
"Type": "varchar",
"Precision": 2147483647,
"Scale": 0,
"Nullable": "UNKNOWN",
"CaseSensitive": true
}
]
}
},
"UpdateCount": 0
}
The above output is an example output, but a similar outcome is what I'm expecting. When I run in AWS CLI:
aws athena --region "us-west-2" get-query-results --query-execution-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111
I get the expected output, so I'm unable to understand why I can't get the same result via lambda.
Thank you so much for all the help! :)
It actually looks like the code is fine. Looking at the response is shows that there is an Object within the ResultSet.Rows. Try to stringify the result before logging such that the handler looks like this:
exports.handler = function(event, context, callback) {
athena.getQueryResults({
QueryExecutionId: "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"
},function(err,data){
if (err) console.log(err);
else {
console.log("Body: ", JSON.stringify(data, null, 2));
}
});
}

Mapping array of objects to an array of Objects with object and array

I have an object
const response = {
"message": "story records found successfully",
"result": [
{
"created_AT": "Thu, 13 Jan 2022 17:37:04 GMT",
"created_BY": "avinash",
"dateTime": "Thu, 13 Jan 2022 17:37:04 GMT",
"deleted_BY": "",
"flag": 0,
"project_ID": "infobot1234",
"stories": {
"steps": [
{
"intent": "test"
},
{
"action": "uttence_test_heading"
},
{
"intent": "fruits"
},
{
"intent": "testintent"
},
{
"action": "utter_txt1234"
},
{
"action": "uttence_test_heading"
},
{
"action": "utter_txt1234"
},
{
"intent": "test"
},
{
"intent": "fruits"
},
{
"action": "uttence_test_heading"
},
{
"intent": "my_localities12333qqqwq"
}
],
"story": "happy path rdedd"
},
"stories_ID": "f5728c4f-3717-40c2-8419-265d5d59bfd1",
"updated_BY": "",
"user_ID": "av1234"
}
],
"status_code": 0
}
From this I have to create a structure like, so my expected output is
const data = [
{intent: 'test', actions:['uttence_test_heading']},
{intent:'fruits', actions:[]},
{intent:"testintent", actions:["utter_txt1234","uttence_test_heading","utter_txt1234"]},
{intent:"test", actions:[]},
{intent:"fruits", actions:["uttence_test_heading"]},
{intent: "my_localities12333qqqwq", actions:[]}
]
The closest that I could get was using response.result[0].stories.steps which gives me the result
[{
intent: "test"
}, {
action: "uttence_test_heading"
}, {
intent: "fruits"
}, {
intent: "testintent"
}, {
action: "utter_txt1234"
}, {
action: "uttence_test_heading"
}, {
action: "utter_txt1234"
}, {
intent: "test"
}, {
intent: "fruits"
}, {
action: "uttence_test_heading"
}, {
intent: "my_localities12333qqqwq"
}]
How can I achieve my expected result do I have to use some condition or something like Object.keys and then apply any condition, because for each intent there is an action and if there is no action then it should be an empty array.
How can I achieve my expected result please guide !
You need to iterate through each array element using the reduce array method, and check if the element is an intent. If it is, push a new object to the result array, if it isn't, just push a new element to the actions array of the last index intent using the .at() method:
const steps = [
{"intent": "test"},
{"action": "uttence_test_heading"},
{"intent": "fruits"},
{"intent": "testintent"},
{"action": "utter_txt1234"},
{"action": "uttence_test_heading"},
{"action": "utter_txt1234"},
{"intent": "test"},
{"intent": "fruits"},
{"action": "uttence_test_heading"},
{"intent": "my_localities12333qqqwq"}
];
const result = steps.reduce((acc, e) => {
if (Object.keys(e)[0] === "intent") {
acc.push({ ...e, actions: [] });
}else {
acc.at(-1).actions.push(e.action)
}
return acc;
}, []);
console.log(result)

Can elasticsearch with node, update only a certain field without rewrite?

My document has a field that looks like this:
_source:
...
"produto_tags" : [
{
"id_produto_cor" : "1623153806",
"tags" : []
},
{
"id_produto_cor" : "875623985732",
"tags": []
},
{...}
...
I need to insert on this field another Object without rewrite the entire produto_tags
data to be inserted:
{
"id_produto_cor" : "312411",
"tags": []
},
and my final document will looks like this:
_source:
...
"produto_tags" : [
{
"id_produto_cor" : "1623153806",
"tags" : []
},
{
"id_produto_cor" : "875623985732",
"tags": []
},
{
"id_produto_cor" : "312411",
"tags": []
}
]
Im using NODE js, I`m using this but it rewrites what I put :
const query = {
doc: {
nome_relatorio: nome_relatorio,
produto_tags: produto_tags,
referencia_tags: referencia_tags,
}
};
return await esClient.update({
index: indexName,
body: query,
id: id,
method: 'post',
type: typeDoc,
})
1. You can use update_by_query api
POST <index_name>/_update_by_query
{
"script": {
"source": "ctx._source.produto_tags.add(params.product)",
"params": {
"product": {
"product_id": "1004600287",
"tags": []
}
}
},
"query": {
"match_all": {} --> select the document
}
}
2. Update api
POST <index_name>/_update/<doc_id>
{
"script": {
"source": "ctx._source.produto_tags.add(params.product)",
"lang": "painless",
"params": {
"product": {
"product_id": "11",
"tags": []
}
}
}
}

JSON schema validation is failing in Postman even if it's valid

I need to validate following response against JSON schema. The problem is it's always failing even if schema is valid.
{
"items": [
{
"uuid": "f68ad4ba-a11e-485d-a2d7-17b9b07bd8d3",
"name": "Code",
"type": "app_code",
"description": "Code 1",
"content_type": "application/javascript",
"audit": {
"created_date": "2017-11-02T00:16:58.000Z",
"created_by": "e7c97dc1-08eb-45ef-b883-d100553bac5c"
}
},
{
"uuid": "3c9e59b0-f6c7-4788-8a14-0b3e99fc4306",
"name": "Object demo 2",
"type": "app_code",
"description": "Object demo 2 description",
"content_type": "application/javascript",
"audit": {
"created_date": "2017-11-02T13:48:22.000Z",
"created_by": "e7c97dc1-08eb-45ef-b883-d100553bac5c"
}
},
{
"uuid": "e2f54e6c-a158-4f43-a332-1c99bb76684e",
"name": "toolbox_test_results",
"type": "toolbox_tests",
"description": "This is snapshots for React-OSS Toolbox",
"content_type": "application/json",
"audit": {
"created_date": "2017-11-07T11:29:02.000Z",
"created_by": "e7c97dc1-08eb-45ef-b883-d100553bac5c"
}
}
],
"metadata": {
"total": 124,
"count": 3
},
"links": [
{
"rel": "self",
"href": "http://microsvcs.star2star.net:10010/users/e7c97dc1-08eb-45ef-b883-d100553bac5c/objects?load_content=false&limit=3&offset=0"
},
{
"rel": "first",
"href": "http://microsvcs.star2star.net:10010/users/e7c97dc1-08eb-45ef-b883-d100553bac5c/objects?load_content=false&limit=3&offset=0"
},
{
"rel": "next",
"href": "http://microsvcs.star2star.net:10010/users/e7c97dc1-08eb-45ef-b883-d100553bac5c/objects?load_content=false&limit=3&offset=3"
},
{
"rel": "last",
"href": "http://microsvcs.star2star.net:10010/users/e7c97dc1-08eb-45ef-b883-d100553bac5c/objects?load_content=false&limit=3&offset=123"
}
]
}
I use following code for validation in Postman:
// Define the JSON Schema
const objectSchema = {
"items": [
{
"audit": {
"created_by": "string",
"created_date": "string",
"updated_by": "string",
"updated_date": "string"
},
"content": {},
"content_type": "string",
"description": "string",
"name": "string",
"type": "string",
"uuid": "string"
}
],
"links": [
{
"href": "string",
"rel": "string",
"templated": true
}
],
"metadata": {}
};
pm.test("JSON schema validation", function() {
var responseData = JSON.parse(responseBody);
var result = tv4.validate(responseData, objectSchema, false, true);
if (result !== true) {
console.log('Schema validation failed:', tv4.error);
}
pm.expect(result).to.be.true;
console.log(JSON.stringify(result));
});
How it's possible to get the detailed error in console (for example: which field has wrong type or missing)? Actual error from console:
message:"Unknown property (not in schema)"
name:"ValidationError"
type:"Error
"
Thank you in advance for answers!
Elaborating on #Pavlo's comment:
In your test:
pm.test("JSON schema validation", function() {
var responseData = JSON.parse(responseBody);
var result = tv4.validate(responseData, objectSchema, false, true);
if (result !== true) {
console.log('Schema validation failed:', tv4.error);
}
pm.expect(result).to.be.true;
console.log(JSON.stringify(result));
});
the line var responseData = JSON.parse(responseBody); should be replaced with:
var responseData = pm.response.json();
Also, from this answer you can add the following line to get more information about where the schema failed:
console.log(tv4.error.dataPath);

Categories