I have a nodeJS application that I have a javascript array of objects. On my jade page I spit them out but now I want to add a filter input that when I type it will start to filter the model that is passed in. Can I do this with Node itself or should I implement something like Knockout JS to create observable arrays? If so does someone have a link to a tutorial to use KO with NodeJS?
JS Array Object
var sections = [
{
title: 'Verity Monitoring',
links: [
{
name: 'Verity ',
link: '#'
},
{
name: 'Hits',
link: '#'
},
{
name: 'Verity Hits Line Chart with Ratios',
link: '#'
},
{
name: 'Verity Cache Performance',
link: '#'
},
{
name: 'Verity Usage for a Date ',
link: '#'
},
]
},
{
title: 'Solr Monitoring',
links: [
{
name: 'Solr Requests',
link: '#'
},
{
name: 'Solr Errors Stores',
link: '#'
},
{
name: 'Solr Timeouts',
link: '#'
},
{
name: 'Solr Average Response Time',
link: '#'
}
]
}
];
exports.sections = sections;
Related
I am using Node.js 16.17 and Express.
Forgive me if this is answered elsewhere, if a solution exists elsewhere, please point me in that direction.
On my server side, I have an array with objects with properties and their values. I want to be able to remove specific text/string from the property values.
What I Have
I currently have an array with objects (and sometimes arrays and object nested within):
DataArray =
[
{
page: {
results: [
{
id: '1234',
title: 'TextIWantA **(Text) I Dont Want**',
children: {
page: {
results: [
{
id: '5678',
title: 'ChildA TextIWant **(Text I) Dont Want**',
},
{
id: '9101',
title: 'ChildB TextIWant **(Text I) Dont Want**',
children: {
page: {
results: [
{
id: 'abcd',
title: 'GrandchildA TextIWant **(Text I (Dont) Want**',
}
]
}
}
},
],
},
},
},
{
id: '1121',
title: 'TextIWantB **(Text) I Dont Want**',
}
]
}
}
]
I am able to flatten this structure with this function:
function flatten(arr) {
const flattened = []
for (const { children, ...element } of arr) {
flattened.push(element)
if (children) {
flattened.push(...flatten(children.page.results))
}
}
return flattened;
}
const flat = [{ page: { results: flatten(DataArray[0].page.results) } }]
console.log(flat[0].page.results)
The returned data is:
[
{ id: '1234', 'page', title: 'TextIWantA **(Text) I Dont Want**' },
{ id: '5678', 'page', title: 'ChildA TextIWant **(Text I) Dont Want**' },
{ id: '9101', 'page', title: 'ChildB TextIWant **(Text I) Dont Want**' },
{ id: 'abcd', 'page', title: 'GrandchildA TextIWant **(Text I (Dont) Want**' },
{ id: '1121', 'page', title: 'TextIWantB **(Text) I Dont Want**' }
]
I am making an assumption that I have to change my text to a string in order to replace it then parse it again to turn back into an object. I'm happy to learn my assumption is true or incorrect, if incorrect, how to fix to be able to remove text.
So if I try to do a replace using the following, 1) it does not work and 2) it does not differentiate for the different text to remove (perhaps I just run multiple/different replaces/filters?):
const veryFlat = flat;
var veryFlatData = veryFlat.map(function(x){return x.toString().replace(/ **(Text) I Dont Want**/g, '');});
var removedTextData= JSON.parse(veryFlatData);
console.log(removedTextData);
Desired Result
I want to be able to remove all of the variances of Text I Dont Want, so the end result would look like (of now it will be flattened as seen above)
DataArray =
[
{
page: {
results: [
{
id: '1234',
title: 'TextIWantA',
children: {
page: {
results: [
{
id: '5678',
title: 'ChildA TextIWant',
},
{
id: '9101',
title: 'ChildB TextIWant',
children: {
page: {
results: [
{
id: 'abcd',
title: 'GrandchildA TextIWant',
}
]
}
}
},
],
},
},
},
{
id: '1121',
title: 'TextIWantB',
}
]
}
}
]
Each title is unique and I don't seem able to find anything to even say I've tried this or that.
I don't want to use .startswith or .length or .index and would prefer to avoid regex, and the example above using .replace doesn't seem to work.
How do I reach into these property values and rip out the text I don't want?
Thank you for any help you can provide.
I have docs in elastic search having no id field in them, I have some other field _id as a unique identifier.
I want to update the doc by _id field via nodejs client, but it is throwing an error Missing required parameter: id
One solution can be, to reindex the whole doc.
Any other suggestions are welcome
I am using following query
await esClient.updateByQuery({
index: 'storyv2',
refresh: true,
body: {
script: {
lang: 'painless',
source: 'ctx._source.like = 100',
},
query: {
match: {
_id: storyId,
},
},
},
});
Elastic version: 2.2
Elastic nodejs client version: 7.10.0
You can also update your documents by query:
POST your-index/_update_by_query
{
"script": {
"source": " ...do something to your document... ",
"lang": "painless"
},
"query": {
"term": {
"unique-id-field": "the-doc-id-to-update"
}
}
}
UPDATE:
await esClient.updateByQuery({
index: 'storyv2',
type: '_doc', <--- add this
refresh: true,
body: {
script: {
lang: 'painless',
source: 'ctx._source.like = 100',
},
query: {
match: {
_id: storyId,
},
},
},
});
I'm trying to add a tag to my AWS Spot Request. But it has returned me { UnexpectedParameter: Unexpected key 'TagSpecifications' found in params.LaunchSpecification.
I have followed this documentation, and I have already tried to move this code out of LaunchSpecification, but the error persists.
const params = {
InstanceCount: 1,
LaunchSpecification: {
ImageId: config.aws.instanceAMI,
KeyName: 'backoffice',
InstanceType: config.aws.instanceType,
SecurityGroupIds: [config.aws.instanceSecurityGroupId],
TagSpecifications: [{
ResourceType: 'instance',
Tags: [{
Key: 'Type',
Value: 'Mongo-Dump',
}],
}],
BlockDeviceMappings: [{
DeviceName: '/dev/xvda',
Ebs: {
DeleteOnTermination: true,
SnapshotId: 'snap-06e838ce2a80337a4',
VolumeSize: 50,
VolumeType: 'gp2',
Encrypted: false,
},
}],
IamInstanceProfile: {
Name: config.aws.instanceProfileIAMName,
},
Placement: {
AvailabilityZone: `${config.aws.region}a`,
},
},
SpotPrice: config.aws.instancePrice,
Type: 'one-time',
};
return ec2.requestSpotInstances(params).promise();
Something makes me think that the problem is in the documentation or in the aws-sdk for Javascript itself. My options are exhausted.
The error message is correct. According to the documentation, the RequestSpotLaunchSpecification object doesn't have an attribute called TagSpecifications.
However, you can tag your Spot Instance request after you create it.
ec2.requestSpotInstances(params) returns an array of SpotInstanceRequest objects, each containing a spotInstanceRequestId (e.g. sir-012345678). Use the CreateTags API with these Spot Instance request ids to add the tags.
const createTagParams = {
Resources: [ 'sir-12345678' ],
Tags: [
{
Key: 'Type',
Value: 'Mongo-Dump'
}
]
};
ec2.createTags(createTagParams, function(err, data) {
// ...
});
I am trying to figure out how to query the nested objects inside the Components object. The data was inserted from a parsed json file.
Query
var query = {}
cursor = db.collection("workflows").find(query).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
This data is returned when I run the query above:
At this point i'm just trying to get it to filter in some manner. I've tried Name:'Test WF' and other variations of that but still can't get a filtered response.
[ { _id: 5c77040838f9d322b89bbd82,
texto:
{ _id: 12,
LocalCachePath: 'Z:\\Test\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } },
{ _id: 5c7704164413692978a9dd1a,
texto:
{ _id: 'Workflow-2019.02.22-23.21.15-MKRU',
LocalCachePath: 'Z:\\MAITest\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } },
{ _id: 5c77046335b012379c99951b,
texto:
{ _id: '154',
LocalCachePath: 'Z:\\Test\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } },
{ _id: 5c7704787bde6f36543d1016,
texto:
{ _id: 'Workflow-2019.02.22-23.21.15-MKRU',
LocalCachePath: 'Z:\\Test\\Cache',
SharedCachePath: [],
Name: 'Test WF',
Desc: 'I\'m testing',
Components: [Array] } } ]
Any insight would be helpful i'm stumbling through this one step at a time.
Here's another query that is giving me results but i guess my issue is going to be to parse out my results as variables.
var query = {'texto.Components.0.Name' : {$gt: ''}}
// var query = {'testo.Name' : {$gt: ''} }
cursor = db.collection("workflows").find(query).toArray(function(err, result) {
if (err) throw err;
Use dot notation (e.g. texto.Name) to query and retrieve fields from nested objects, example:
var query = {'texto.Name': 'Test WF'}
Simply
db.getCollection('TestQueries').find({'texto.Name': 'Test WF'})
Regex used for Case Insensitive.
db.getCollection('TestQueries').find({"texto.Name":{
'$regex' : '^test wa$', '$options' : 'i'
}})
Using collation
db.fruit.createIndex( {"texto.Name": 1},{ collation: {
locale: 'en', strength: 2
} } )
db.getCollection('TestQueries').find(
{ "texto.Name": "test wa" } ).collation( { locale: 'en', strength: 2 }
)
You can also use $elemMatch. It is longer, but allows for multiple fields query.
db.getCollection('TestQueries').find({texto: {$elemMatch: {Name: "test wa"} }))
Official docs here
Trying to send QR codes via email with mandrill. Here's what I've got so far:
db.get(id, function (err, doc) {
if (err) { fail('Couch', [err, doc]) }
db.attachment.get(id, 'qr-code.png', function (error, image) {
// Base64 encode the image.
var base64 = 'data:image/png;base64,' + new Buffer(image).toString('base64');
Up to this point, I'm good. base64 can be used in an html img tag to render the qr code, woohoo! The bit I'm having trouble with is next...
// Email Tickets to client
mandrill('/messages/send-template', {
template_name: 'qr-confirm',
template_content: [],
template_content is supposed to be empty if I'm just using merge_vars right?
message: {
to: [{email: doc.email, name: doc.name}],
from_email: 'events#example.com',
from_name: 'The Team',
subject: "QR codes attached",
tags: ['qr'],
merge_vars: [{
rcpt: doc.email,
vars: [
{ name: "name", content: doc.name },
{ name: "attendee", content: doc.id },
{ name: "purchaser", content: doc.purchaser }
]
}],
Okay, do I need both attachments and images or if I use images will it automatically attach them?
attachments: [
{type: "image/png", name: "qr-code.png", content: base64}
],
images: [
{type: "image/png", name: "qr-code.png", content: base64}
],
}
}, function(error, manReply) { console.log(error || manReply) }); // manReply, haha
});
});
Okay, so with all that, I still get a broken attachment. There's an attachment, it's just broken 1kb, and not rendering inline either.
Any help would rock!!
Okay, problem solved, just don't include data:image/png;base64, in the content parameter : )